How to inject JavaScript callback to detect onclick event, using iOS WKWebView?

前端 未结 4 1606
灰色年华
灰色年华 2021-02-01 06:14

I\'m using a WKWebView to show a website which has some HTML that includes three buttons. I want to run some Swift code in the native app when a specific button is

4条回答
  •  Happy的楠姐
    2021-02-01 06:23

    You can always inject source code using evaluateJavaScript(_:) on the web view. From there, either replace the event handler on the buttons (posting a message and then invoking the original function in the new handler) or add an event handler on the buttons or an ancestor element that captures click events and posts a message. (The original event handler will also run.)

    document.getElementById("submit-button").addEventListener("click", function () {
       window.webkit.messageHandlers.log.postMessage("submit");
    });
    

    If the buttons don’t have an ID, you can add a handler on the document that captures all (bubbling) click events and then posts a message based on the event target (using the button’s text or location as a determinant).

提交回复
热议问题