Robin Chauhan
Robin Chauhan

Reputation: 1

Webview loading url but opening content in default browser?

It opens my link in Webview but when I try to open hyperlinks and content of the web or navigation link, it starts opening with the default browser.

public class MainActivity extends Activity {

    private WebView mWebView;

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mWebView = findViewById(R.id.activity_main_webview);


        mWebView.setWebViewClient(new WebViewClient());

        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);


         mWebView.loadUrl("http://");
    }

    @Override
    public void onBackPressed() {
        if(mWebView.canGoBack()) {
            mWebView.goBack();
        } else {
            super.onBackPressed();
        }
    }

}

class MyWebViewClient extends WebViewClient {

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if (Objects.requireNonNull(Uri.parse(url).getHost()).endsWith("http://www.ieltsmadeeasy.tk/")) {
        return false;
    }

    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    view.getContext().startActivity(intent);
    return true;
}

}

I want to browse the whole website inside the web view, not any browser please help me

Upvotes: 0

Views: 271

Answers (1)

ThexXTURBOXx
ThexXTURBOXx

Reputation: 391

Here is some documentation about WebViews: https://developer.android.com/guide/webapps/webview#java

The problem is, that you don't override the shouldOverrideUrlLoading(view, url) function of the WebViewClient, as you use the default one.

If you use this as the WebViewClient, it should work (copied from examples in documentation):

private class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (Uri.parse(url).getHost().equals("https://www.example.com")) {
            // This is my website, so do not override; let my WebView load the page
            return false;
        }
        // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        startActivity(intent);
        return true;
    }
}

So, just take this class and change the line mWebView.setWebViewClient(new WebViewClient()); to mWebView.setWebViewClient(new MyWebViewClient());

Upvotes: 1

Related Questions