Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the Id of clicked element in a WebKit view?

Tags:

ios

swift

webkit

I have a UIWebKit loaded in an url and I want to pick the id of a html element when clicked. I can get the element when I know the id but how to get an unknown element Id when it is clicked. thank you for helping me !

like image 582
hamza mansour Avatar asked Sep 03 '25 13:09

hamza mansour


1 Answers

You can do it following way.

  1. Inject some javascript into the WebView using WKUserScript.
  2. Injected javascript will listen to document body for any click event.
  3. Upon an click event received, find the DOM element using elementFromPoint.
  4. Setup that way, javascript will communicate with native code.
  5. Upon receiving clicks and finding the element, contact native code for clicked DOM.

I've tested this way of working & it works for me.

import UIKit
import WebKit

class ViewController: UIViewController {

    @IBOutlet weak var webView: WKWebView!
    private var url = URL(string: "https://www.google.com")!


    override func viewDidLoad() {
        super.viewDidLoad()

        initializeWebView()
        loadData()

    }

    private func initializeWebView() {

        let javascript = """
        window.onload = function() {
            document.addEventListener("click", function(evt) {
                var tagClicked = document.elementFromPoint(evt.clientX, evt.clientY);
                window.webkit.messageHandlers.jsMessenger.postMessage(tagClicked.outerHTML.toString());
            });
        }
        """

        let userScript = WKUserScript.init(source: javascript,
                                           injectionTime: .atDocumentStart, forMainFrameOnly: true)
        webView.configuration.userContentController.addUserScript(userScript)
        webView.configuration.userContentController.add(self, name: "jsMessenger")
    }

    private func loadData() {
        let request  = URLRequest(url: url)
        webView?.load(URLRequest.init(url: url))
    }
}


extension ViewController: WKScriptMessageHandler {
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        print(message.body)
    }
}

It gives you the whole element as string

like image 161
Ratul Sharker Avatar answered Sep 05 '25 01:09

Ratul Sharker