创建WKUserContentController
实例后更改WKWebView
时。这是我的代码。
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
为什么会这样?
实际上,无论是什么错误或什么东西,当我用代码编写时,这都是可以的。但是,当我将其与情节提要一起使用时,这使我感到困扰。情节提要实例化WKUserContentController
WKWebView
答案 0 :(得分:1)
不要更换用户内容控制器。只需使用网络视图已具有的视图即可:
let script = // whatever
let config = webView.configuration
config.userContentController.addUserScript(script)
即使网络视图来自情节提要,该方法也仍然有效。