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

前端 未结 4 1556
灰色年华
灰色年华 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条回答
  •  走了就别回头了
    2021-02-01 06:38

    You can inject JS code using evaluateJavaScript() function to the WKWebView. You can capture all onclick events with following JS code, which detect only the click on submit button. All original event handlers will also run - don't worry!

    document.addEventListener("click", function(e)
    {
        e = e || window.event;
        //if(e.target.value == 'Submit') //you can identify this button like this, but better like:
        if(e.target.getAttribute('onclick') == 'javascript:GotoURL(3)')
        //if this site has more elements with onclick="javascript:GotoURL(3)"
        //if(e.target.value == 'Submit' && e.target.getAttribute('onclick') == 'javascript:GotoURL(3)')
        {
            console.log(e.target.value);
            //if you need then you can call the following line on this place too:
            //window.webkit.messageHandlers.log.postMessage("submit");
        }
    });
    
    //DO NOT add the next line in your code! It is only for my demo - buttons need this in my demo for execution
    function GotoURL(site){}//DO NOT add this line! It is only for my demo!
    
    
    

提交回复
热议问题