Detect inside Android Browser or WebView

The question:

How can Javascript detect whether a website is loaded in Android’s stock browser or loaded in a WebView of another app? I would like to run slightly different code in these two cases.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Activity -> onCreate

this.webView.getSettings().setUserAgentString(
    this.webView.getSettings().getUserAgentString() 
    + " "
    + getString(R.string.user_agent_suffix)
);

Res -> Values -> strings.xml

<string name="user_agent_suffix">AppName/1.0</string>

Javascript

function() isNativeApp {
    return /AppName/[0-9.]+$/.test(navigator.userAgent);
}

Method 2

You can check the server variables on the page that is being requested to see if it is coming from your app and set a javascript variable accordingly

if($_SERVER['HTTP_X_REQUESTED_WITH'] == "com.company.app")
    echo 'var isAndroidApp=true;';
else
    echo 'var isAndroidApp=false;';
  • replace com.company.app with your package name

Method 3

In the newer versions of WebView, Lollipop and above, you can differentiate the WebView by looking for the wv field in user agent string:

Mozilla/5.0 (Linux; Android 5.1.1; Nexus 5 Build/LMY48B; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/43.0.2357.65 Mobile Safari/537.36

https://developer.chrome.com/multidevice/user-agent#webview_user_agent


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment