How to “Monitor”the URL base in WebView

烈酒焚心 提交于 2020-01-03 03:50:05

问题


So i want to be able to monitor the URL my WebView application is loading. The main thing im trying to accomplish is to keep the WebView inside a specific Website or at least by able to detect when the user is leaving the website's URL.

Example. If i have the base URL of www.google.com and when the user clicks Images, he gets "http://www.google.com/imghp" However it still has the base URL of www.google.com, so if there is a way to monitor when the base URL is no longer www.google.com, such as when a user clicks a search result and is then brought to a different website completely.

The purpose of doing this is that i want to display to the user a dialog or Toast to let them know they are leaving the website that this WebView app is created for.

Any Code, Idea's or suggestions would be greatly appreciated.

Example Code

 @Override
 public void onLoadResource(WebView view, String url)
    {
        if (url.equals("http://www.google.com"))
        {
            //do your own thing here
            view.loadUrl(url);
        }
        else
        {
            AlertDialog.Builder localBuilder2 = new AlertDialog.Builder(Webview_Main.this);
            localBuilder2.setTitle("Hey Wait!");
            localBuilder2.setMessage("You currently are about to leave the website\n\nIf you want to stay inside this website, Please click the Go Back button below");
            localBuilder2.setIcon(R.drawable.ic_launcher);
            localBuilder2.setPositiveButton("Go Back",
                    new DialogInterface.OnClickListener() {
                public void onClick(
                        DialogInterface paramDialogInterface,
                        int paramInt) {
                    web.goBack();
                }
            });
            localBuilder2.setNegativeButton("Continue",
                    new DialogInterface.OnClickListener() {
                public void onClick(
                        DialogInterface paramDialogInterface,
                        int paramInt) {

                }
            });

            localBuilder2.show();
        };
            super.onLoadResource(view, url);
        }    

However this above code doesnt work, only keeps poping up the alert dialog since the URL maybe different.


回答1:


I have resolved my issue with the following code.

 @Override
 public boolean shouldOverrideUrlLoading(WebView view, String url) {
           if (url.startsWith("http://www.google.com"))
            { view.loadUrl(url);
            progressBar.setVisibility(View.VISIBLE);
            }
          else
            { Toast.makeText(getBaseContext(),
            "Your about to leave Google.com",
            Toast.LENGTH_LONG).show();
    }
 }

Thanks @MH. for the suggestion



来源:https://stackoverflow.com/questions/15937907/how-to-monitorthe-url-base-in-webview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!