javascript 检测android webview
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31848320/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Detect android webview
提问by Megi Ben Nun
I have an html-javascript
page, and I need to detect whenever it open on web view (Like inside facebook webview, twitter webview, etc.), and if it a webview - display another content.
我有一个html-javascript
页面,我需要检测它何时在 web 视图中打开(比如在 facebook webview、twitter webview 等中),如果它是 webview - 显示另一个内容。
Note:I do not control the third-party Android apps, so I cannot make changes to their code.
注意:我不控制第三方 Android 应用程序,因此我无法更改它们的代码。
I already found a way to detect an IOS webview (Found it on stackoverflow):
我已经找到了一种检测 IOS webview 的方法(在 stackoverflow 上找到):
var isIosWebview =/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(navigator.userAgent)
var isIosWebview =/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(navigator.userAgent)
Now I'm looking for a javascript code that can detect Android web view.
现在我正在寻找可以检测 Android 网页视图的 javascript 代码。
Help?
帮助?
回答by Mikhail Naganov
You can't detect it by only using the user agent string, as any app that uses WebView can set the UA string to anything it wants.
您不能仅使用用户代理字符串来检测它,因为任何使用 WebView 的应用程序都可以将 UA 字符串设置为它想要的任何内容。
If you still insist on using the UA string, this is the explanation of the official docs: initially, Chromium-based WebView was using .0.0.0
as Chrome version suffix; in the newer versions ; wv
was added into the platform part of the UA string. Note that pre-KitKat WebViews didn't have the Chrome
part. See older posts about that: Android, webview user agent vs browser user agent
如果你仍然坚持使用UA字符串,官方文档的解释是这样的:最初,基于Chromium的WebView.0.0.0
作为Chrome版本后缀使用;在较新版本; wv
中添加到 UA 字符串的平台部分。请注意,KitKat 之前的 WebViews 没有该Chrome
部分。请参阅关于此的旧帖子:Android、webview 用户代理与浏览器用户代理
Another hint of WebView involvement is presence of X-Requested-With
HTTP header with an application package name. Note that this header is also set by XMLHttpRequest, so you need to look for the actual value of the header.
WebView 参与的另一个提示是存在X-Requested-With
带有应用程序包名称的HTTP 标头。注意这个header也是由XMLHttpRequest设置的,所以你需要查找header的实际值。
The statement that WebView doesn't support iframes is not correct.
WebView 不支持 iframes 的说法是不正确的。
回答by silvanasono
I know how to do it. It is very simple. Because there is an object used by Android web view to trigger functions in its Android app via javascript. So in your js code you can use:
我知道该怎么做。这很简单。因为 Android 网络视图使用一个对象通过 javascript 触发其 Android 应用程序中的功能。所以在你的 js 代码中你可以使用:
if (typeof Android === "undefined") {
// do something if is NOT a web view
} else {
// do something else if is a web view
}