cmltkt
cmltkt

Reputation: 193

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?

Upvotes: 3

Views: 4011

Answers (2)

Mujah Maskey
Mujah Maskey

Reputation: 8804

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

Upvotes: 7

kajot
kajot

Reputation: 303

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?

Upvotes: 0

Related Questions