khcpietro
khcpietro

Reputation: 1539

addUserScript is not working after WKWebView is initialized

When I change WKUserContentController after WKWebView instance created. Here is my code.

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

Above code works fine, but below is not

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

Why this happens?
In fact, it's okay when I write in code, whatever it's bug or something. However, this bothers me when I use this with storyboard. I cannot change WKUserContentController after storyboard instantiate WKWebView

Upvotes: 4

Views: 2633

Answers (1)

matt
matt

Reputation: 535316

Don't replace the user content controller. Just use the one that the web view already has:

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

That works even if the web view came from a storyboard.

Upvotes: 7

Related Questions