Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect inside Android Browser or WebView

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.

like image 729
JoJo Avatar asked Jul 21 '11 21:07

JoJo


People also ask

What is the difference between WebView and browser?

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.

Is Android WebView a 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.


2 Answers

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); } 
like image 135
JoJo Avatar answered Sep 21 '22 17:09

JoJo


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
like image 37
Sean Avatar answered Sep 21 '22 17:09

Sean