Michal_196 Michal_196 - 1 year ago 96
Java Question

Open external browser in webview?

I am trying to run twitter in webview, but whenever i try to catch external link to open some default browser nothing happens, it's like app has stalled.

Example:- If i click on some blog link inside twitter webview, nothing happens.

I have tried this,

private class InsideWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView View, String url) {
if( url.startsWith("https://mobile.twitter.com") || url.startsWith("https://m.twitter.com") ) {
MoviesFragment.this.progress.setProgress(0);
View.loadUrl(url);
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity( intent );
return true;
}


}


but nothing happens, when i try to capture log, there is nothing about webview in it please help.

UPDATE

This time i took a different approach, but still the same result.

This time i created a context menu to catch HTML link and then divert them to external browser, but this time also in twitter nothing happens. A popup appears to
open in browser
after clicking it nothing happens.

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);

WebView w = (WebView)v;
WebView.HitTestResult result = w.getHitTestResult();
if(result.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
menu.addSubMenu(0, 0, 0, "open in browser");
}
}

@Override
public boolean onContextItemSelected(MenuItem item){
if (item.getTitle()=="open in browser") {//open the actual page into using the browser
myWebView.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(myWebView.getUrl())));
}
return true;
}

Answer Source

SOLVED

The problem was String URL was catching the new URL, that's why only home page was opening after triggering open in browser.

Implemented HitTestResult and then it was a piece of cake.

private String url = "";




 protected void onCreate(Bundle savedInstanceState) {
.........................................
.......................................
............................
}


@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
    super.onCreateContextMenu(menu, v, menuInfo);

    WebView w = (WebView)v;
    WebView.HitTestResult result = w.getHitTestResult();


    if(result.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE)
    {
        menu.addSubMenu(4, 4, 4, "Open in browser");
        url = result.getExtra();

    }

}

@Override
public boolean onContextItemSelected(MenuItem item){
    if (item.getTitle()=="Open in browser"){

        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        startActivity(browserIntent);
    }

    return true;
}

I hope someone will find it useful.