当我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
Run Code Online (Sandbox Code Playgroud)
上面的代码工作正常,但下面不是
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
Run Code Online (Sandbox Code Playgroud)
为什么会发生这种情况?
其实我写代码的时候,不管是bug什么的,都可以。但是,当我将它与故事板一起使用时,这让我感到困扰。WKUserContentController故事板实例化后我无法更改WKWebView
不要替换用户内容控制器。只需使用 Web 视图已有的一个:
let script = // whatever
let config = webView.configuration
config.userContentController.addUserScript(script)
Run Code Online (Sandbox Code Playgroud)
即使 Web 视图来自故事板,这也有效。
| 归档时间: |
|
| 查看次数: |
1303 次 |
| 最近记录: |