Last active
November 17, 2023 15:56
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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