简体   繁体   中英

How to manipulate DOM in UIWebView in iOS

I am using a UIWebView in my app. I want to call a objective-c function when user clicks a link in a website in UIWebView. Is there a way to do this? Does UIWebView allow to change it?

First hook it. [yourwebview setDelegate:self]

Use the following delegate method

webView:shouldStartLoadWithRequest:navigationType

Like:

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
    NSURL *url = request.URL;
    NSString *urlString = url.absoluteString;
    //put your logic here, like 
    if (![url.scheme isEqual:@"yourscheme"]) {// or query contains or [url absolutestring] contains etc
        return NO;
    }
    return YES;
}

If you want to manipulate DOM or call any function of UIWebView, then use:

[yourwebView stringByEvaluatingJavaScriptFromString:@"alert('hello')"];
[yourwebView stringByEvaluatingJavaScriptFromString:@"$('#domid').hide();"];

Just as stated in other answers, you should use webview delegate's

webView:shouldStartLoadWithRequest:navigationType 

method to smuggle some data from within the WebView. You can read my verbose answer on this topic here: how to use javascript in uiwebview to get the clicked button id?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM