Detect if page is loaded inside WKWebView in JavaScript

后端 未结 5 1251
闹比i
闹比i 2020-12-02 19:10

How can I reliably detect using javascript that a page is loaded inside a WKWebView? I\'d like to be able to detect these scenarios:

  • iOS & WKWebView
  • <
5条回答
  •  感情败类
    2020-12-02 20:05

    Given the change in behavior to the UIWebView that was introduced by Apple in iOS 10, here's a new answer that combines the original response by @Justin-Michael and the follow-up favorite by @hexalys.

    var isWKWebView = false ;
    if( navigator.platform.substr(0,2) === 'iP' ) {    // iOS detected
        if( window.webkit && window.webkit.messageHandlers ) {
            isWKWebView = true ;
        }
    }
    

    It turns out that Justin's answer was really the better feature detection mechanism, because it works for both iOS 9 and iOS 10.

    No telling what happens when we get to iOS 11. :-)


    Qualification: this test will work if you are using the official Cordova WKWebView plugin to build your webview app, because that plugin does initialize the addScriptMessageHandler method, as noted by @hexalys in the comments to this post. That mechanism is being used by Cordova to define a new JS to native bridge when the WKWebView plugin is present.

    Search for addScriptMessageHandler in that plugin repo and see the very end of the ios-wkwebview-exec.js file in that repo for some implementation details (or search for the string window.webkit.messageHandlers in that file).

提交回复
热议问题