Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save nerzh/b02b939f1d7acf3913eeecfe97c64c7b to your computer and use it in GitHub Desktop.
Save nerzh/b02b939f1d7acf3913eeecfe97c64c7b 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