andr111 andr111 - 11 months ago 282
iOS Question

Detect if page is loaded inside WKWebView in JavaScript

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

  • not iOS

There is a similar question about UIWebView here. But it's quite old and I'm not sure if same still applies to WKWebView.

Answer Source

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;