Saturday, March 23, 2024
HomeiOS Developmentjavascript - WKWebview js injection

javascript – WKWebview js injection


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:

  1. 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`
  1. load web site.

if let url = URL(string: "https://instance.com/new") { webView.load(URLRequest(url: url)) }

  1. 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');
            });
    """)`
  1. 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)
}`
  1. 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()
        }
    }
}`



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments