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
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!