Sukhchain Singh
Sukhchain Singh

Reputation: 844

Open External Links inside Webview

I want to open a webview with POST data. So I am doing this:

webView = (WebView) findViewById(R.id.dashboard);
String url = "http://www.example.test";
String postData = "json=" + JSON;
webView.postUrl(url, postData.getBytes());

So now when I launch this webview, clicking on links open a default browser of device, is there any way to stick to webview for opening links?
I researched but all of them are for GET requests.

Upvotes: 0

Views: 1192

Answers (2)

Amin Keshavarzian
Amin Keshavarzian

Reputation: 3943

Here is how to do it in Kotlin:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            myWebView.webViewClient = object : WebViewClient() {
                override fun shouldOverrideUrlLoading(
                    view: WebView,
                    request: WebResourceRequest
                ): Boolean {
                    view.loadUrl(request.url.toString())
                    return false
                }
            }
        } else {
            myWebView.webViewClient = object : WebViewClient() {
                override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                    view?.loadUrl(url.toString())
                    return false
                }
            }
        }

Upvotes: 1

Sukhchain Singh
Sukhchain Singh

Reputation: 844

So i found the solution it is pretty much same for both GET and POST requests.

    webView = (WebView) findViewById(R.id.dashboard);

    String url = "http://www.example.test";
    String postData = "json=" + JSON;

    webView.postUrl(url,postData.getBytes());

    webView.setWebViewClient(new WebViewClient() {
        public boolean shouldOverrideUrlLoading(WebView viewx, String urlx) {
            viewx.loadUrl(urlx);
            return false;
        }
    });

Upvotes: 0

Related Questions