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 clicked.
About the HTML
The three buttons look like this:
<input type="button" value="Edit Info" class="button" onclick="javascript:GotoURL(1)">
<input type="button" value="Start Over" class="button" onclick="javascript:GotoURL(2)">
<input type="button" value="Submit" class="button" onclick="javascript:GotoURL(3)">
The GotoURL
function they call looks like this:
function GotoURL(site)
{
if (site == '1')
document.myWebForm.action = 'Controller?op=editinfo';
if (site == '2')
document.myWebForm.action = 'Controller?op=reset';
if (site == '3')
document.myWebForm.action = 'Controller?op=csrupdate';
document.myWebForm.submit();
}
Current WKWebView
Implementation
When I click any of the buttons in the webview, this function is called on my WKNavigationDelegate
:
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
// ...?
}
But of course, navigation
is opaque and therefore contains no information about which of the three buttons the user clicked.
What's the simplest way to detect when this button is clicked?
I want to respond when the user clicks Submit and ignore other button presses.
I see some other approaches on Stack Overflow using WKUserContentController
, but they appear to require the web site to call something like:
window.webkit.messageHandlers.log.postMessage("submit");
I do not control this website so I cannot add this line in its source code, and I don't know the best way to inject it in the correct place using WKWebView
.