Search code examples
androidandroid-studiowebviewpopupads

How can I block ad/popup/domain


How can I block ad/popup/domain

Hello, I'm making a simple webview and I would like that in this webview I could limit which domains my user can access, for example, I would like only google.com and youtube.com to be accessed, how can I do this?

Is this the best way to block popup and advertisement?

public class MainActivity extends AppCompatActivity {

    WebView wv;

    public void onBackPressed(){
        if(wv.canGoBack()){
            wv.goBack();
        }else{
            super.onBackPressed();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        wv = (WebView) findViewById(R.id.webView);
        //Enable Javascript
        wv.getSettings().setJavaScriptEnabled(true);
        wv.setFocusableInTouchMode(true);
        // set Render Priority to high
        wv.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
        wv.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
        wv.getSettings().setDomStorageEnabled(true);
        wv.getSettings().setAppCacheEnabled(true);
        wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);

        // Load url
        wv.loadUrl("https://www.google.com/");
        wv.setWebViewClient(new myWebViewClient());
    }

    String currentUrl;

    private class myWebViewClient extends WebViewClient{

        @Override
        public void onLoadResource(WebView view, String url) {
            Log.e("Resource ",url);
        }

    }


}

Solution

  • Before calling loadUrl, just perform checks on the String. If it is anything other than you want, display something like a snackbar with the message