简体   繁体   English

检测网站是在Android浏览器中运行还是在应用程序的webView中运行

[英]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 更新:感谢您的回答,但我想澄清一下我是一名javascript开发人员而不是Android应用程序开发人员,我需要在运行时检测网站是在Android浏览器中加载还是加载到应用程序的WebView中,通过JavaScript代码

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? 原始问题:当我不对应用程序负责时,Javascript如何在运行时检测网站是在Android浏览器中加载还是加载到应用程序的WebView中?

I believe that the user agent will be the same for both the browser and the webview so that won't tell the difference. 我相信浏览器和webview的用户代理将是相同的,因此无法区分。

What you can do however is to attempt to bind javascript code to android code and call it. 但你可以做的是尝试将javascript代码绑定到android代码并调用它。 If it succeeds then its running in webview, or if it fails then its in browser. 如果成功则在webview中运行,或者如果它失败则在浏览器中运行。

For more information on how to do this see: 有关如何执行此操作的详细信息,请参阅:

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

Example (Java/Javascript may not be right): 示例(Java / Javascript可能不正确):

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

Set the WebView variable to false then attempt to run the function. 将WebView变量设置为false然后尝试运行该函数。

Then check that WebView boolean to confirm whether its in the app or browser. 然后检查WebView布尔值以确认它是在应用程序还是浏览器中。

EDIT: Here is another example: Detect inside Android Browser or WebView 编辑:这是另一个例子: 在Android浏览器或WebView中检测

One solution could be to add something to the WebView user agent, so anything else without the special identifier would come from somewhere else. 一种解决方案可能是向WebView用户代理添加内容,因此没有特殊标识符的任何其他内容都将来自其他位置。

You can change the WebView user agent like this: 您可以像这样更改WebView用户代理:

//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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM