检测是否在JavaScript中的WKWebView内加载了页面
问题描述:
如何使用javascript可靠地检测到在WKWebView中加载页面?我希望能够检测到这些情况:
How can I reliable detect using javascript that a page is loaded inside a WKWebView? I'd like to be able to detect these scenarios:
- iOS& WKWebView
- iOS& Safari
- 不是iOS
有一个类似的问题关于UIWebView 此处。但它已经很老了,我不确定WKWebView是否仍然适用。
There is a similar question about UIWebView here. But it's quite old and I'm not sure if same still applies to WKWebView.
答
你可以检查是否存在 window.webkit.messageHandlers
WKWebKit用于从JavaScript接收消息。如果它存在,你在 WKWebView
里面。
You can check for the existence of window.webkit.messageHandlers
which WKWebKit uses to receive messages from JavaScript. If it exists, you're inside a WKWebView
.
结合简单的用户代理检查应该做技巧:
That combined with a simple user agent check should do the trick:
var iOS = (navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false);
var isWKWebView = false;
if (window.webkit && window.webkit.messageHandlers) {
isWKWebView = true;
}