Natalie Gabel
Natalie Gabel

Reputation: 51

Detect whether a website runs in Android browser or webView of an app

Update: thanks for the answers, but I want to clarify that I am a javascript developer and not an android app developer, and I need to detect on runtime whether a website is loaded in Android's browser or loaded in a WebView of an app, only by javascript code

Original Question: How can Javascript detect on runtime whether a website is loaded in Android's browser or loaded in a WebView of an app, when I am not in charge on the application?

Upvotes: 5

Views: 3953

Answers (2)

OneRainbow
OneRainbow

Reputation: 41

I believe that the user agent will be the same for both the browser and the webview so that won't tell the difference.

What you can do however is to attempt to bind javascript code to android code and call it. If it succeeds then its running in webview, or if it fails then its in browser.

For more information on how to do this see:

http://developer.android.com/guide/webapps/webview.html#BindingJavaScript

Example (Java/Javascript may not be right):

@JavascriptInterface
public void userAgentDetect() {
    WebView = true;
}

Set the WebView variable to false then attempt to run the function.

Then check that WebView boolean to confirm whether its in the app or browser.

EDIT: Here is another example: Detect inside Android Browser or WebView

Upvotes: 2

255kb - Mockoon
255kb - Mockoon

Reputation: 6974

One solution could be to add something to the WebView user agent, so anything else without the special identifier would come from somewhere else.

You can change the WebView user agent like this:

//get current user agent
String userAgent = myWebView.getSettings().getUserAgentString();    
//add something
userAgent = userAgent + " my_website_is_in_a_webview";    
//save the new user agent
myWebView.getSettings().setUserAgentString(userAgent);

Upvotes: 1

Related Questions