IOS UIWebView: How to add listeners to DOM events?

Solutions Collect From Internet About “IOS UIWebView: How to add listeners to DOM events?”

Yes, you can do this with crafted url and UIWebViewDelegate methods.

First, to add event listener on button tag, you should execute javascript like below (after the page is loaded)

// In the UIWebViewDelegate
- (void)webViewDidFinishLoad:(UIWebView *)webView {
    if (/* when the loaded url is the target */) {
        NSString *js = @"document.getElementById('button').click = function() { window.location = 'my-protocol://dummmy.com/maybe/some/data';}";
        [webView stringByEvaluatingJavaScriptFromString: js];
    }
}

We bind a click event on the button, and when it’s clicked, it will trigger a request to webView.

And the next thing we gotta do is to intercept the request and do what you want in ObjC.

// In the UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    if (/* when the url of the request is the crafted url */) {
        // call your objc method...
    }
}