Javascript in WKWebView – evaluateJavaScript vs addUserScript

I am trying to understand the best way to execute javascript with WKWebview

Could someone please give me the use cases / best practices when using WKWebView.

  • wkwebview with location services
  • Disable entire UIMenuController edit menu in WKWebView
  • Detect when WKWebView has finished loading EVERY time
  • Launching phone/email/map links in WKWebView
  • iOS 9 … Are WebView(s) exempt from the App Transport Security Exceptions (ATS) rules that block insecure HTTP hosts?
  • drops 113 error: Could not find specified service
  • When to use addUserScript and WKScriptMessageHandler and when to use evaluateJavaScript

        let jscript = "my script"
        let userScript = WKUserScript(source: jscript, injectionTime: .atDocumentEnd, forMainFrameOnly: true)
        let userContentController = WKUserContentController()
        let webViewConfiguration = WKWebViewConfiguration()
        webViewConfiguration.userContentController = userContentController
        webView = WKWebView(frame: self.view.bounds, configuration: webViewConfiguration)


    let myScript
    self.wkWebView.evaluateJavaScript(script) { (result, error) in
        if error != nil {

    2 Solutions Collect From Internet About “Javascript in WKWebView – evaluateJavaScript vs addUserScript”

    In my experience, WKUserScript seems to have more privileges, eg:
    document.cookie=”test=test” works with WKUserScript but not with evaluateJavaScript.

    However, WKUserScript requires an additional reload() for the javascript you injected to run. It maybe a bug. Sometimes it complicates the code.

    WKScriptMessageHandler is a separate thing. It allows your native app to receive messages from javascript. eg, you can add a handler and receives message that is posted from javascript like: “window.webkit.messageHandlers.notification.postMessage({body: “…”});”

    Pretty cool stuff that doesn’t exist in UIWebView

    Found a nice explanation

    2.3.2 Inject javascript from native code to js DOM
    emphasized text
    WKUserContentController allows add (and remove) a WKUserScript to be injected either when the DOM tree starts to load or finishes to load. On the contrary, evaluateJavaScript allows application to execute a javascript snippet on demand at any time.