I have a WebView in my app that displays a page not belonging to me. My desired behavior is, if any link is tapped by the user, the device's Browser app is launched, and the resulting page is loaded there. Unfortunately, this page is doing some weird things, so shouldOverrideUrlLoading()
does not fire.
My attempted solution is to hook some javascript into pushState and use an interface to run Android code to launch the browser app.
Here is my interface:
public class LaunchExternalBrowserHack {
Context mContext;
LaunchExternalBrowserHack(Context c) {
mContext = c;
}
@JavascriptInterface
public void launchExternalBrowser(String url) {
openUrl(url);
}
}
I'm injecting some javascript into the page in onPageFinished()
:
public void onPageFinished(WebView view, String url) {
mWebView.loadUrl(javascript);
}
Here is my javascript:
private final String javascript = "javascript:history.pushState = function (state, title, url) { console.log(url); console.log(location.href); Uphoria.launchExternalBrowser(location.origin, url); };";
And, of course, I'm adding the interface to the WebView
:
mWebView.addJavascriptInterface(new LaunchExternalBrowserHack(getContext()), "Android");
So this seems to work. The Browser app is launching and the next page is opening.
However, the WebView is also moving forward, too. I want to prevent this, but I cannot find a way to prevent the WebView moving forward while still allowing me to capture the forwarding url and launch the Browser app. As I mentioned earlier, with this webpage, shouldOverrideUrlLoading
is not firing.
Ideas?