2

In the Android app with the WebView and WebViewClient configured, after the window.open(url, '_system') called from the js, the js event window.beforeunload is fired before the Android WebViewClient.shouldOverrideUrlLoading is called. Is this a proper and intended behavior? Is there a way to intercept the url open without the window.beforeunload event fired?

Maksym Gontar
  • 22,765
  • 10
  • 78
  • 114

1 Answers1

1

see this example code, maybe help you:

    final WebView webView = (WebView)findViewById(R.id.webview);

    // Enable javascript
    webView.getSettings().setJavaScriptEnabled(true);

    webView.setWebViewClient(new WebViewClient() {

        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            final Uri uri = Uri.parse(url);
            return customUriHanlder(uri);
        }

        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            final Uri uri = request.getUrl();
            return customUriHanlder(uri);
        }

        private boolean customUriHanlder(final Uri uri) {
            Log.i(TAG, "Uri =" + uri);
            final String host = uri.getHost();
            final String scheme = uri.getScheme();
            // you can set your specific condition
            if (true) {
                // Returning false means that you are going to load this url in the webView itself
                return false;
            } else {
                // Returning true means that you need to handle what to do with the url
                // open web page in a Browser
                final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
                return true;
            }
        }

    });

    // Load the webpage
    webView.loadUrl("https://google.com/");

with customUriHanlder function you can load your url in vebview itself or in browser.
on google documentation shouldOverrideUrlLoading: If a WebViewClient is provided, returning true causes the current WebView to abort loading the URL, while returning false causes the WebView to continue loading the URL as usual.

Taher Fattahi
  • 951
  • 1
  • 6
  • 14