Skip to content

Instantly share code, notes, and snippets.

@iosappdeveloper
Last active November 17, 2023 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save iosappdeveloper/84c144cbae0a127a90bd82d9519a4ac2 to your computer and use it in GitHub Desktop.
Save iosappdeveloper/84c144cbae0a127a90bd82d9519a4ac2 to your computer and use it in GitHub Desktop.
Add event listener from iOS code and then get callback in native code
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print("\(#function): \(message)")
}
func setupSubViews() {
let configurations = WKWebViewConfiguration()
let controller = WKUserContentController()
let myEventScriptString =
"""
var elements = document.getElementsByClassName('button');
for (var i = 0 ; i < elements.length; i++) {
elements[i].addEventListener('click', function() {
window.webkit.messageHandlers.myEvent.postMessage(JSON.stringify(true));
});
}
"""
let myEventScript = WKUserScript(source: myEventScriptString, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
controller.addUserScript(myEventScript)
controller.add(self, name: "myEvent")
configurations.userContentController = controller
configurations.allowsInlineMediaPlayback = true
webView = WKWebView(frame: .zero, configuration: configurations)
// Layout.add(webView, in: view!)
webView.navigationDelegate = self
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment