As you all know the UIWebview is deprecated in the iOS 8.0 and above versions. So we have to use WKWebview to show URLs and other data. WKWebview is an object that displays interactive web content, such as for an in-app browser.
Example:
To add observers you need to insert javascript into the webpage or you can also insert this at the server-side. In the below code the source is depended on the need i.e. on which button or task you have to perform the action. Here we have added the script that runs on the click of any button.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
override func viewDidLoad() { super.viewDidLoad() let preferences = WKPreferences() let contentController = WKUserContentController() preferences.javaScriptEnabled = true let source: String = """ window.onload = function() { document.addEventListener("click", function(evt) { var tagClicked = document.elementFromPoint(evt.clientX, evt.clientY); window.webkit.messageHandlers.btnClicked.postMessage(tagClicked.outerHTML.toString()); }); } """ let script: WKUserScript = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: true) contentController.addUserScript(script) let configuration = WKWebViewConfiguration() configuration.preferences = preferences configuration.userContentController = contentController configuration.userContentController.add(self, name: "btnClicked") self.webView = WKWebView(frame: self.view.frame, configuration: configuration) webView.allowsBackForwardNavigationGestures = true self.webView.uiDelegate = self self.webView.navigationDelegate = self self.webView.scrollView.delegate = self self.view = webView } |
When you have inserted the script into the webpage then you need to handle the messageHandlers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
extension ViewController: WKScriptMessageHandler { func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { print(message.name) switch message.name { case "btnClicked": if let sentData = message.body { print(sentData) //Perform you desired action here. } default: break } } } |
You can know more about WKWebview from here.
Thank you!!!