Example usage for android.webkit WebChromeClient WebChromeClient

List of usage examples for android.webkit WebChromeClient WebChromeClient

Introduction

In this page you can find the example usage for android.webkit WebChromeClient WebChromeClient.

Prototype

WebChromeClient

Source Link

Usage

From source file:com.ben.gank.fragment.WebFragment.java

private void initWebView() {
    mWebView.setWebViewClient(new WebViewClient() {
        @Override/*from  ww w .  j  a v a  2  s  .  c  o m*/
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //trueWebViewfalse??
            view.loadUrl(url);
            return true;
        }
    });
    mWebView.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                // ?
                if (mProgressBar != null && mSwipeRefreshLayout != null) {
                    mProgressBar.setVisibility(View.GONE);
                    mProgressBar.setProgress(0);
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            } else {
                // 
                if (mProgressBar != null) {
                    mProgressBar.setVisibility(View.VISIBLE);
                    mProgressBar.setProgress(newProgress);
                }
            }
        }
    });
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    mWebView.getSettings().setSupportZoom(true);
    mWebView.getSettings().setDisplayZoomControls(true);

}

From source file:com.androidquery.simplefeed.PQuery.java

private void debug(WebView wv) {
    wv.setWebChromeClient(new WebChromeClient() {
        public boolean onConsoleMessage(ConsoleMessage cm) {
            AQUtility.debug(cm.message() + " -- From line " + cm.lineNumber() + " of " + cm.sourceId());
            return true;
        }/*from ww w.j  av  a 2s .c  om*/
    });
}

From source file:com.nineducks.hereader.ui.NewsItemsFragment.java

private void initUI() {
    Log.d("hereader", "Creating UI");
    webViewContainer = (FrameLayout) getActivity().findViewById(R.id.webview_container);
    mDualPane = webViewContainer != null && webViewContainer.getVisibility() == View.VISIBLE;
    actionBar = (ActionBar) getActivity().findViewById(R.id.action_bar);
    actionBar.setHomeIcon(R.drawable.hackful_icon);
    actionBar.addAction(new LoadFrontpageItemsAction(HackfulReaderActivity.getContext(), this));
    actionBar.addAction(new LoadNewItemsAction(HackfulReaderActivity.getContext(), this));
    actionBar.addAction(new LoadAskItemsAction(HackfulReaderActivity.getContext(), this));
    actionBar.addAction(new AboutAction(HackfulReaderActivity.getContext(), this));
    if (mDualPane || getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        actionBar.setTitle(R.string.app_name);
    }/*  ww  w .  jav a 2s  . c  o m*/
    if (mDualPane) {
        if (webView == null) {
            Log.d("hereader", "WebView is null, creating new instance");
            final ActionBar actionB = actionBar;
            webView = new WebView(getActivity());
            webView.setId(R.id.webview_id);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.getSettings().setSupportZoom(true);
            //webView.getSettings().setBuiltInZoomControls(false);
            webView.setWebChromeClient(new WebChromeClient() {

                @Override
                public void onProgressChanged(WebView view, int newProgress) {
                    if (newProgress == 100) {
                        actionB.setProgressBarVisibility(View.GONE);
                    }
                }

            });
        }
        webViewContainer.addView(webView, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    }
    Log.d("hereader", "UI created");
}

From source file:com.msopentech.thali.utilities.android.AndroidXmlHttpRequestTestActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    webView = new WebView(this);
    //TODO: Oh, this is all a huge security hole.
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setAllowFileAccessFromFileURLs(true);
    webView.getSettings().setAllowFileAccess(true);
    webView.getSettings().setDomStorageEnabled(true);
    webView.getSettings().setAppCacheEnabled(true);
    webView.getSettings().setDatabaseEnabled(true);
    webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
    webView.getSettings().setAllowContentAccess(true);
    webView.getSettings().setLoadsImagesAutomatically(true);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        WebView.setWebContentsDebuggingEnabled(true);
    }/* w ww.  j a  v a  2  s. c o m*/
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            Log.e("xmlhttptest", "errorCode: " + errorCode + ", description: " + description + ", failingUrl: "
                    + failingUrl);
            super.onReceivedError(view, errorCode, description, failingUrl);
        }
    });
    webView.setWebChromeClient(new WebChromeClient() {
        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage) {
            Log.e("xmlhttptest", consoleMessage.message() + " - " + consoleMessage.messageLevel().toString()
                    + " - " + consoleMessage.lineNumber() + " - " + consoleMessage.sourceId());
            return false;
        }
    });

    bridgeManager = new AndroidBridgeManager(this, webView);
}

From source file:it.rignanese.leo.slimtwitter.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // setup the sharedPreferences
    savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    setContentView(R.layout.activity_main);

    //setup the floating button
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override//w w w.  jav  a2  s.c  o m
        public void onClick(View view) {
            webViewTwitter.scrollTo(0, 0);//scroll up
        }
    });

    // setup the refresh layout
    swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
    swipeRefreshLayout.setColorSchemeResources(R.color.officialAzureTwitter, R.color.darkAzureSlimTwitterTheme);// set the colors
    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            refreshPage();//reload the page
            swipeRefresh = true;
        }
    });

    // setup the webView
    webViewTwitter = (WebView) findViewById(R.id.webView);
    setUpWebViewDefaults(webViewTwitter);//set the settings

    goHome();//load homepage

    //WebViewClient that is the client callback.
    webViewTwitter.setWebViewClient(new WebViewClient() {//advanced set up

        // when there isn't a connetion
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            String summary = "<html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" /></head><body><h1 "
                    + "style='text-align:center; padding-top:15%;'>" + getString(R.string.titleNoConnection)
                    + "</h1> <h3 style='text-align:center; padding-top:1%; font-style: italic;'>"
                    + getString(R.string.descriptionNoConnection)
                    + "</h3>  <h5 style='text-align:center; padding-top:80%; opacity: 0.3;'>"
                    + getString(R.string.awards) + "</h5></body></html>";
            webViewTwitter.loadData(summary, "text/html; charset=utf-8", "utf-8");//load a custom html page

            noConnectionError = true;
            swipeRefreshLayout.setRefreshing(false); //when the page is loaded, stop the refreshing
        }

        // when I click in a external link
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url == null || url.contains("twitter.com")) {
                //url is ok
                return false;
            } else {
                //if the link doesn't contain 'twitter.com', open it using the browser
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            }
        }

        //START management of loading
        @Override
        public void onPageFinished(WebView view, String url) {
            swipeRefreshLayout.setRefreshing(false); //when the page is loaded, stop the refreshing
            super.onPageFinished(view, url);
        }
        //END management of loading

    });

    //WebChromeClient for handling all chrome functions.
    webViewTwitter.setWebChromeClient(new WebChromeClient() {
        //to upload files
        //thanks to gauntface
        //https://github.com/GoogleChrome/chromium-webview-samples
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                WebChromeClient.FileChooserParams fileChooserParams) {
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }
            mFilePathCallback = filePathCallback;

            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getBaseContext().getPackageManager()) != null) {
                // Create the File where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                }

                // Continue only if the File was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }

            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");

            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);

            return true;
        }
    });
}

From source file:no.barentswatch.fiskinfo.MapActivity.java

@SuppressLint({ "SetJavaScriptEnabled" })
private void configureWebParametersAndLoadDefaultMapApplication() {
    browser = new WebView(getContext());
    browser = (WebView) findViewById(R.id.browserWebView);
    browser.getSettings().setJavaScriptEnabled(true);
    browser.getSettings().setDomStorageEnabled(true);
    browser.getSettings().setGeolocationEnabled(true);
    browser.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

    browser.addJavascriptInterface(new JavaScriptInterface(getContext()), "Android");
    browser.setWebViewClient(new barentswatchFiskInfoWebClient());
    browser.setWebChromeClient(new WebChromeClient() {

        public void onGeolocationPermissionsShowPrompt(String origin,
                GeolocationPermissions.Callback callback) {
            Log.d("geolocation permission", "permission >>>" + origin);
            callback.invoke(origin, true, false);
        }/*from w  w w  .  j av  a2s.c  o m*/

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            Log.i("my log", "Alert box popped");
            return super.onJsAlert(view, url, message, result);
        }
    });
    updateMapTools();
    browser.loadUrl("file:///android_asset/mapApplication.html");

}

From source file:com.directsiding.android.WebActivity.java

/**
 * Configuracin del WebView//ww w.j av a  2 s .c om
 */
private void webViewConfig() {
    webView.getSettings().setBuiltInZoomControls(true);

    // Para HoneyComb o mayor, sacamos los controles del zoom
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        webView.getSettings().setDisplayZoomControls(false);
    }

    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {
            mProgressBar.setProgress(progress);
        }
    });

    webView.setWebViewClient(new DirectSidingWebViewClient());

    webView.setDownloadListener(new DownloadListener() {
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype,
                long contentLength) {

            String filename = getFileName(contentDisposition);

            Toast.makeText(WebActivity.this, "Iniciando descarga ...", Toast.LENGTH_SHORT).show();
            new DownloadFile(WebActivity.actualNotifyId++, filename).execute(url);

        }
    });
}

From source file:com.wellsandwhistles.android.redditsp.fragments.WebViewFragment.java

@SuppressLint("NewApi")
@Override/*  w  w  w .j  a  v a  2 s.  c o m*/
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
        final Bundle savedInstanceState) {

    mActivity = (AppCompatActivity) getActivity();

    CookieSyncManager.createInstance(mActivity);

    outer = (FrameLayout) inflater.inflate(R.layout.web_view_fragment, null);

    webView = (WebViewFixed) outer.findViewById(R.id.web_view_fragment_webviewfixed);
    final FrameLayout loadingViewFrame = (FrameLayout) outer
            .findViewById(R.id.web_view_fragment_loadingview_frame);

    /*handle download links show an alert box to load this outside the internal browser*/
    webView.setDownloadListener(new DownloadListener() {
        @Override
        public void onDownloadStart(final String url, String userAgent, String contentDisposition,
                String mimetype, long contentLength) {
            {
                new AlertDialog.Builder(mActivity).setTitle(R.string.download_link_title)
                        .setMessage(R.string.download_link_message)
                        .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                Intent i = new Intent(Intent.ACTION_VIEW);
                                i.setData(Uri.parse(url));
                                getContext().startActivity(i);
                                mActivity.onBackPressed(); //get back from internal browser
                            }
                        }).setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                mActivity.onBackPressed(); //get back from internal browser
                            }
                        }).setIcon(android.R.drawable.ic_dialog_alert).show();
            }
        }
    });
    /*handle download links end*/

    progressView = new ProgressBar(mActivity, null, android.R.attr.progressBarStyleHorizontal);
    loadingViewFrame.addView(progressView);
    loadingViewFrame.setPadding(General.dpToPixels(mActivity, 10), 0, General.dpToPixels(mActivity, 10), 0);

    final WebSettings settings = webView.getSettings();

    settings.setBuiltInZoomControls(true);
    settings.setJavaScriptEnabled(true);
    settings.setJavaScriptCanOpenWindowsAutomatically(false);
    settings.setUseWideViewPort(true);
    settings.setLoadWithOverviewMode(true);
    settings.setDomStorageEnabled(true);
    settings.setDisplayZoomControls(false);

    // TODO handle long clicks

    webView.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, final int newProgress) {

            super.onProgressChanged(view, newProgress);

            General.UI_THREAD_HANDLER.post(new Runnable() {
                @Override
                public void run() {
                    progressView.setProgress(newProgress);
                    progressView.setVisibility(newProgress == 100 ? View.GONE : View.VISIBLE);
                }
            });
        }
    });

    if (mUrl != null) {
        webView.loadUrl(mUrl);
    } else {
        webView.loadDataWithBaseURL("https://reddit.com/", html, "text/html; charset=UTF-8", null, null);
    }

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(final WebView view, final String url) {

            if (url == null)
                return false;

            if (url.startsWith("data:")) {
                // Prevent imgur bug where we're directed to some random data URI
                return true;
            }

            // Go back if loading same page to prevent redirect loops.
            if (goingBack && currentUrl != null && url.equals(currentUrl)) {

                General.quickToast(mActivity,
                        String.format(Locale.US, "Handling redirect loop (level %d)", -lastBackDepthAttempt),
                        Toast.LENGTH_SHORT);

                lastBackDepthAttempt--;

                if (webView.canGoBackOrForward(lastBackDepthAttempt)) {
                    webView.goBackOrForward(lastBackDepthAttempt);
                } else {
                    mActivity.finish();
                }
            } else {

                if (RedditURLParser.parse(Uri.parse(url)) != null) {
                    LinkHandler.onLinkClicked(mActivity, url, false);
                } else {
                    webView.loadUrl(url);
                    currentUrl = url;
                }
            }

            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);

            if (mUrl != null && url != null) {

                final AppCompatActivity activity = mActivity;

                if (activity != null) {
                    activity.setTitle(url);
                }
            }
        }

        @Override
        public void onPageFinished(final WebView view, final String url) {
            super.onPageFinished(view, url);

            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {

                    General.UI_THREAD_HANDLER.post(new Runnable() {
                        @Override
                        public void run() {

                            if (currentUrl == null || url == null)
                                return;

                            if (!url.equals(view.getUrl()))
                                return;

                            if (goingBack && url.equals(currentUrl)) {

                                General.quickToast(mActivity, String.format(Locale.US,
                                        "Handling redirect loop (level %d)", -lastBackDepthAttempt));

                                lastBackDepthAttempt--;

                                if (webView.canGoBackOrForward(lastBackDepthAttempt)) {
                                    webView.goBackOrForward(lastBackDepthAttempt);
                                } else {
                                    mActivity.finish();
                                }

                            } else {
                                goingBack = false;
                            }
                        }
                    });
                }
            }, 1000);
        }

        @Override
        public void doUpdateVisitedHistory(WebView view, String url, boolean isReload) {
            super.doUpdateVisitedHistory(view, url, isReload);
        }
    });

    final FrameLayout outerFrame = new FrameLayout(mActivity);
    outerFrame.addView(outer);

    return outerFrame;
}

From source file:au.com.wallaceit.reddinator.TabCommentsFragment.java

@SuppressLint({ "SetJavaScriptEnabled", "AddJavascriptInterface" })
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mContext = this.getActivity();
    SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);
    global = (GlobalObjects) mContext.getApplicationContext();
    final boolean load = getArguments().getBoolean("load");

    // get needed activity values
    articleId = getActivity().getIntent().getStringExtra(WidgetProvider.ITEM_ID);
    permalink = getActivity().getIntent().getStringExtra(WidgetProvider.ITEM_PERMALINK);

    ll = new LinearLayout(mContext);
    ll.setLayoutParams(new WebView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT, 0, 0));
    // fixes for webview not taking keyboard input on some devices
    mWebView = new WebView(mContext);
    mWebView.setLayoutParams(new WebView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.MATCH_PARENT, 0, 0));
    ll.addView(mWebView);/*  www. j av a  2 s.c  o m*/
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true); // enable ecmascript
    webSettings.setDomStorageEnabled(true); // some video sites require dom storage
    webSettings.setSupportZoom(false);
    webSettings.setBuiltInZoomControls(false);
    webSettings.setDisplayZoomControls(false);
    int fontSize = Integer.parseInt(mSharedPreferences.getString("commentfontpref", "18"));
    webSettings.setDefaultFontSize(fontSize);
    webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);

    mSharedPreferences.getString("titlefontpref", "16");

    final String themeStr = global.mThemeManager.getActiveTheme("appthemepref").getValuesString();
    mWebView.setWebViewClient(new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            boolean redditLink = false;
            System.out.println(url);
            if (url.indexOf("file://") == 0) { // fix for short sub and user links
                url = url.replace("file://", "https://www.reddit.com") + "/.compact";
                redditLink = true;
            }
            if (redditLink || url.indexOf("https://www.reddit.com/") == 0) {
                Intent i = new Intent(mContext, WebViewActivity.class);
                i.putExtra("url", url);
                startActivity(i);
            } else {
                Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(i);
            }
            return true; // always override url
        }

        public void onPageFinished(WebView view, String url) {
            mWebView.loadUrl("javascript:init(\"" + StringEscapeUtils.escapeJavaScript(themeStr) + "\", \""
                    + global.mRedditData.getUsername() + "\")");
            if (load)
                load();
        }
    });
    mWebView.setWebChromeClient(new WebChromeClient());

    mWebView.requestFocus(View.FOCUS_DOWN);
    WebInterface webInterface = new WebInterface(mContext);
    mWebView.addJavascriptInterface(webInterface, "Reddinator");

    mWebView.loadUrl("file:///android_asset/comments.html#" + articleId);
}

From source file:com.chatwingsdk.fragments.CommunicationMessagesFragment.java

private void setupWebView() {
    mWebview.setWebViewClient(new WebViewClient() {
        @Override/* w w  w  .  j a  v  a  2  s .co m*/
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            try {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            } catch (Exception e) {
                return false;
            }
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            //TODO should be when page start rendering chatbox
            LogUtils.v("Loading page DONE");
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            LogUtils.v("Loading page Oh no! " + description);
        }
    });

    mWebview.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            LogUtils.v("Loading page " + newProgress + ":" + mWebview);
        }
    });
    WebSettings webSettings = mWebview.getSettings();
    webSettings.setAppCacheEnabled(false);
    webSettings.setJavaScriptEnabled(true);
    mWebview.addJavascriptInterface(mFayeJsInterface, ChatWingJSInterface.CHATWING_JS_NAME);
}