Search code examples
androidandroid-webviewpopupwindow

android : Open pop-up window in my webview


I have webview in my application and I want it to open pop up windows when clicking on a link inside webview. I have added following code but it didn't work:-

WebSettings webSettings = webViewPage.getSettings();    
webSettings.setJavaScriptEnabled(true);    
webSettings.setSupportMultipleWindows(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);

That's how I want pop up window to appear the popup should appear like this


Solution

  • I am answering my own question after 3 long years:

    When a link is touched inside a webpage then depending on a webpage implementation there are two possible scenarios: 1) Link will be opened in same window. 2) Link will be opened in new window.

    Well Its easy to handle 1st scenario using below code:

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    

    Overiding shouldOverrideUrlLoading inside WebViewClient implementation will open link in same window.

    Now lets look at the 2nd case, where webpage is requesting a url to be open in new window. For this case we need to tell our webview to support multiple windows like below:

    webView.getSettings().setSupportMultipleWindows(true);
    

    and then adding a new web chrome client to webview to get event when new window is requested by webpage

    webView.setWebChromeClient(new WebChromeClient() {
    
    
            @Override
            public boolean onCreateWindow(WebView view, boolean isDialog,
                    boolean isUserGesture, Message resultMsg) {
    
    
    
                    WebView newWebView = new WebView(WebpageActivity.this);
                    newWebView.getSettings().setJavaScriptEnabled(true);
                    newWebView.getSettings().setSupportZoom(true);
                    newWebView.getSettings().setBuiltInZoomControls(true);
                    newWebView.getSettings().setPluginState(PluginState.ON);
                    newWebView.getSettings().setSupportMultipleWindows(true);
                    view.addView(newWebView);
                    WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
                    transport.setWebView(newWebView);
                    resultMsg.sendToTarget();
    
                    newWebView.setWebViewClient(new WebViewClient() {
                        @Override
                        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                            view.loadUrl(url);
                            return true;
                        }
                    });
    
                    return true;
                }
            }
    
        });
    

    Cheers!!!