IOS UIWebView: How to add listeners to DOM events?

前端 未结 2 2009
春和景丽
春和景丽 2021-02-06 14:19

How can I add listeners to DOM events in UIWebView? For example for the following html:


         


        
2条回答
  •  独厮守ぢ
    2021-02-06 14:31

    Here is the Swift way to intercept when a Link is clicked in the UIWebView:

    Get yourself a delegate:

    class ViewController: UIViewController, UIWebViewDelegate { //... }
    

    And assign it:

    override func viewDidLoad() {
            super.viewDidLoad()
    
            webView.delegate = self
    
            //...
    }
    

    Now we can use it to intercept:

        func webViewDidFinishLoad(_ webView: UIWebView) {
                if (currentURL?.lowercased().range(of:"some/url") != nil) {
                    webView.stringByEvaluatingJavaScript(from: "document.getElementsByTagName('a')[0].onclick = function() {window.location = 'injected://loadPDF1'; return false;}")
                }
        }
    
        // Sent before a web view begins loading a frame.
        func webView(_: UIWebView, shouldStartLoadWith: URLRequest, navigationType: UIWebViewNavigationType) -> Bool{
            // intercept all injected page calls
            if (shouldStartLoadWith.url?.scheme == "injected") {
                return false;
            }
            return true;
        }
    

提交回复
热议问题