Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addUserScript is not working after WKWebView is initialized

Tags:

ios

wkwebview

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

like image 536
khcpietro Avatar asked Sep 21 '25 10:09

khcpietro


1 Answers

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.

like image 52
matt Avatar answered Sep 23 '25 01:09

matt