I must inject js to deal with shut button in webpage, however it works solely in inital web page, If I am going to a different web page in web site, it simply not dealing with. It cease working after navigation to another web page, even when I navigate again. It not working anymore
What truly I do:
- Configure webview
` let preferences = WKPreferences()
preferences.javaScriptEnabled = true
let configuration = WKWebViewConfiguration()
configuration.preferences = preferences
let userContentController = WKUserContentController()
let supply = """
if (doc.getElementById('closeWebApp')) {
doc.getElementById('closeWebApp').addEventListener('click on', perform() { window.webkit.messageHandlers.ios.postMessage('closeWebApp'); });
}
"""
let script = WKUserScript(supply: supply, injectionTime: .atDocumentStart, forMainFrameOnly: false)
userContentController.addUserScript(script)
userContentController.add(self, identify: "ios")
configuration.userContentController = userContentController
webView = WKWebView(body: view.bounds, configuration: configuration)
webView.navigationDelegate = self`
- load web site.
if let url = URL(string: "https://instance.com/new") { webView.load(URLRequest(url: url)) }
- In delegate methodology deal with closeWebApp aspect occasion click on
`func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript(“””
doc.getElementById('closeWebApp').addEventListener('click on', perform() {
window.webkit.messageHandlers.ios.postMessage('Shut button clicked');
});
""")`
- Additionally wrote inside didStartProvisionalNavigation
` func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
webView.evaluateJavaScript(“””
if (doc.getElementById(‘closeWebApp’)) {
doc.getElementById(‘closeWebApp’).addEventListener(‘click on’, perform() { window.webkit.messageHandlers.ios.postMessage(‘closeWebApp’); });
}
“””) { (consequence, error) in
if let error = error {
print(“JavaScript analysis error: (error.localizedDescription)”)
} else {
print(“JS evaluated successfull”)
}
}
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == .backForward {
onBackPassed = true
}
decisionHandler(.enable)
}`
- Additionally dealing with
`func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
guard let buttonId = message.identify as? String else {
return
}
if buttonId == "ios" {
onBackPassed = true
DispatchQueue.essential.async {
self.onBackPressed()
}
}
}`