How to manipulate DOM in UIWebView in iOS

依然范特西╮ 提交于 2019-12-10 10:04:56

问题


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?


回答1:


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();"];



回答2:


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?



来源:https://stackoverflow.com/questions/16000523/how-to-manipulate-dom-in-uiwebview-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!