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.
What is WebView? Simply put, Android WebView allows apps to display web content, without having to open a web browser. Up to Android 6, WebView was a system service. Then, with Android 7.0, Google incorporated that functionality into the default Chrome Browser.
WebView is powerful because it not only provides the app with an embedded browser, it also allows the developer's app to interact with web pages and other web apps.
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); }
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;';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With