WKWebView 初始化后 addUserScript 不工作

addUserScript is not working after WKWebView is initialized

当我在 WKWebView 个实例创建后更改 WKUserContentController 时。这是我的代码。

let configuration = WKWebViewConfiguration()
let userController = WKUserContentController()
userController.addUserScript(WKUserScript(source: "alert('it works')", injectionTime: .atDocumentEnd, forMainFrameOnly: true))

configuration.userContentController = userController // before instantiate WKWebView

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

view = webView

上面的代码工作正常,但下面的代码不行

let configuration = WKWebViewConfiguration()
let userController = WKUserContentController()
userController.addUserScript(WKUserScript(source: "alert('it doesn't work')", injectionTime: .atDocumentEnd, forMainFrameOnly: true))

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

webView.configuration.userContentController = userController // 
// neither configuration.userContentController = userController

view = webView

为什么会这样?
其实我写代码的时候还好,不管是什么bug什么的。但是,当我将它与情节提要一起使用时,这让我很困扰。我无法在故事板实例化 WKWebView

后更改 WKUserContentController

不要替换用户内容控制器。只需使用网络视图已有的那个:

let script = // whatever
let config = webView.configuration
config.userContentController.addUserScript(script)

即使网络视图来自情节提要,也能正常工作。