How to manipulate DOM in UIWebView in iOS

2019-05-10 20:43发布

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?

2条回答
放荡不羁爱自由
2楼-- · 2019-05-10 21:23

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?

查看更多
爷的心禁止访问
3楼-- · 2019-05-10 21:31

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();"];
查看更多
登录 后发表回答