2

I just build my app with WKWebView with swift 4.0 (iOS 12.1)

I need to run my javascript from online html, However if I move url from index to another page, my print message does not working at all.

    let contentController = WKUserContentController()
    contentController.add(self, name: "myHandler") 

    let configuration = WKWebViewConfiguration()
    configuration.userContentController = contentController

    webview = WKWebView(frame: self.view.frame, configuration: configuration)
    webview.uiDelegate = self
    webview.navigationDelegate = self
    self.view = self.webview


override func viewDidLoad() {
    super.viewDidLoad()
    let url = URL(string: "example.com/index") // of course https://
    let request = URLRequest(url: url!)
    webview.load(request)

I missed userContentController when I move to another html page in the webView. Index page can call this one but another page do not call any function.

index.html(ok) -> link to a.html -> a.html (not ok) -> link to index.html -> index.html(ok)

Do not Call this one :

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    print("call print out")
    if message.name == "myHandler" {
        print("JS -> Native Call \(message.body)")
        abc()
    } else {
        print("JS -> Native N/A")
    }
}

I cannot get any message even "call print out" at all. How can I active userContentController in my code?

Richard
  • 351
  • 4
  • 17
  • Did you added `App Transport Security Settings` in your `info.plist` file? You can have a look to this question: https://stackoverflow.com/questions/32456848/ios9-does-not-load-insecure-resources-from-a-secure-page-ssl-https – axel Apr 12 '19 at 15:18
  • Sure, All of my url is using with https protocol. – Richard Apr 12 '19 at 15:31
  • @axel Finally I found that this was caused by Xcode 10.2 bugs.. Xcode 10.1 do not report any issue for this... :( I appreciate your assist axel :) – Richard Apr 14 '19 at 13:07
  • Glad that you figured it out @Richard – axel Apr 15 '19 at 08:02
  • @Richard do you remember what exactly the issue was or how you found it? I'm running into the same problem, javascript code works on iOS 12 and 12.2 but not on 12.1. Any hints? – André Herculano Jul 11 '19 at 16:28

2 Answers2

2

Javascript must be enabled through WKPreferences. You can specify these in the preferences field of you WKWebViewConfiguration. Javascript is disabled by default.

You simply need to set the javaScriptEnabled field of the preferences object to true. There are several useful settings that can be changed by the preferences object. I would urge you to look at the documentation.

Specifically your code to initialize the WKWebView should look like this.

let contentController = WKUserContentController()
contentController.add(self, name: "myHandler") 

let configuration = WKWebViewConfiguration()
configuration.userContentController = contentController
configuration.preferences = WKPreferences()
configuration.preferences.javaScriptEnabled = true

webview = WKWebView(frame: self.view.frame, configuration: configuration)
webview.uiDelegate = self
webview.navigationDelegate = self
self.view = self.webview

PS You may also want to have a look at this question. I'm not marking yours as a duplicate because your question asks why javascript isn't working, not how to enable it.

EDIT: JavaScript is now enabled by default. This answer is no longer accurate.

William Rosenbloom
  • 2,506
  • 1
  • 14
  • 37
  • @Richard the code snippet you posted tells me that you did not. Are you omitting the lines where you enable js? – William Rosenbloom Apr 13 '19 at 10:24
  • @Richard if you're not sure what I mean by that, I have replaced my previous brief example with a more thorough demonstration of what enabling js should look like. – William Rosenbloom Apr 13 '19 at 19:45
  • @Rosenbloom Oh my god.. what happen to me? My mac pro had Xcode 10.2 cannot resolve this issue but another mac book pro 10.1 had no issue for this.. I think it is a Xcode 10.2 bugs.. Oh my goodness :( Anyway thank you Rosenbloom. – Richard Apr 14 '19 at 13:05
  • @Richard I don’t understand. What was the problem? – William Rosenbloom Apr 14 '19 at 22:18
  • @Richard I am also using the same xcode 10.2. Is this issue regarding this or anything else. And how we can check that our Javascript is loaded? – Ruchira More Aug 12 '19 at 08:58
  • how we can check that our Javascript is loaded? – Ruchira More Aug 12 '19 at 08:59
  • @RuchiraMore You can run check the object itself via something like `NSLog("js enabled = %s", configuration.preferences.javaScriptEnabled ? "true" : "false")` or you could try running a piece of dummy javascript that logs a message if it's able to run. – William Rosenbloom Oct 03 '19 at 18:50
  • @Richard Thank you for your help. I have added this setting for WKWebview. I just triggered alert from JS to check it is loaded or not. This solved my problem – Ruchira More Oct 04 '19 at 06:09
  • The statement in bold "Javascript is disabled by default." in this answer is wrong. **Javascript is enabled by default in WKPreferences** Source: https://developer.apple.com/documentation/webkit/wkpreferences/1536203-javascriptenabled?language=objc – Pierre Jun 30 '20 at 16:28
  • @Dustt thank you for the correction. I have incorporated the change. – William Rosenbloom Jul 08 '20 at 18:46
  • FYI this WKPreferences-based `.javascriptEnabled` flag is deprecated as of iOS 14. It now generates a warning: ''javaScriptEnabled' was deprecated in iOS 14.0: Use WKWebPagePreferences.allowsContentJavaScript to disable content JavaScript on a per-navigation basis` – drewster Oct 19 '21 at 17:41
2

Correct usage as of iOS 14+

let contentController = WKUserContentController()
contentController.add(self, name: "myHandler") 

let configuration = WKWebViewConfiguration()
configuration.userContentController = contentController
configuration.preferences = WKPreferences()

// Here's the new magic for iOS 14:
let webPageDefaultPrefs = WKWebpagePreferences()
webPageDefaultPrefs.allowsContentJavaScript = true
config.defaultWebpagePreferences = webPageDefaultPrefs

webview = WKWebView(frame: self.view.frame, configuration: configuration)
webview.uiDelegate = self
webview.navigationDelegate = self
self.view = self.webview
drewster
  • 5,460
  • 5
  • 40
  • 50