Monday, February 06, 2012

Xcode snippet #3: Injecting JavaScript in UIWebView

How to get, for example, all the hyperlinks from a webpage, which is loaded in your iPhone app using the UIWebView control?
(Xcode's webbrowser counterpart)

Doing this in JavaScript is an easy task. All we have to do is to inject a JavaScript function into the loaded webpage which will do the work for us.

Injecting JavaScript into an UIWebView control can be achieved using the stringByEvaluatingJavaScriptFromString method, which returns the result of a given script. In other words you can run scripts with this method.

In the below example all links from a webpage are extracted and returned as string formatted as href|text|title.

    [webView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');"  
     "script.type = 'text/javascript';"  
     "script.text = \"function getHyperlinks() { " 
     "var links = document.getElementsByTagName('a');"  
     "var allLinks = '';"
     "for (var i = 0; i<links.length; i++) {"
     "var link = links[i].href + '|' + links[i].text + '|' + links[i].title + ';';"
     "allLinks += link;"
     "} return allLinks;"

    NSString *html = [webView stringByEvaluatingJavaScriptFromString: 
    textView.text = html;
In the first step the JavaScript function getHyperlinks() is injected in the HTML document. At last the function is executed and its result is returned into a textview.

That's all!