Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

java - Block a URL in a WebView on Android

I want to block a link from loading within a Webview.

Code

public class WebMy extends Activity {


   
    private WebView mWebview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
            setContentView(R.layout.pantalla);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);  
            
    
             
            mWebview  = new WebView(this);
            mWebview.setWebViewClient(new WebViewClient()); 
            mWebview.getSettings().setJavaScriptEnabled(true); // Enable JavaScript.

            mWebview .loadUrl("http://www.myweb.com");
            setContentView(mWebview );
           
    }

Potential Solution

public class MyWebViewClient extends WebViewClient {
    public boolean shuldOverrideKeyEvent (WebView view, KeyEvent event) {
         // Do something with the event here.
         return true;
    }

    public boolean shouldOverrideUrlLoading (WebView view, String url) {
        if (Uri.parse(url).getHost().equals("www.google.com")) {
             // This is my web site, so do not override; let my WebView load the page.
             return false;
        }

        // Reject everything else.
        return true;
    }
}

I don′t know how I have to use this in my code. For example, if I want to block this url http://www.myweb.com/pepito. How can I do this with this code? Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

shouldOverrideUrlLoading will examine the web page URL loaded into the WebView and all URLs loaded within the page content.

public class MyWebViewClient extends WebViewClient {
    public boolean shouldOverrideKeyEvent (WebView view, KeyEvent event) {
         
         return true;
    }

    public boolean shouldOverrideUrlLoading (WebView view, String url) {
        if (Uri.parse(url).getHost().equals("http://www.myweb.com/pepito")) {
             // This is my web site, so do not override; let the WebView load the page.
             return false;
        }

        // Reject everything else.
        return true;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...