How does uiwebview run javascript JS?

Source: Internet
Author: User

WebKit on the iPhone (Part 1)

If you develop an application which shocould display a web page or HTML file, you can use the WebKit framework, which is part of the MACOs and also of the iPhone OS.

But while on the Mac, the WebKit framework provides almost 160 public header files which define even more public classes and tons of methods you can call to get control of all aspects of loading, rendering, displaying and modifying a Web page, on the iPhone there's only one single class (uiwebview) with has just about a dozen methods you can use. though internally the uiwebview class uses the same WebKit framework that is available on the Mac as public API, this API is private on the iPhone and therefore can't be used. the small number of methods of the uiwebview class are sufficient to display nicely formatted text in help screens for example, but for a Web browser (like ICAB mobile) or other web-based Apps this isn' t enough, too essential features are missing.

Some examples:

  • Uiwebview doesn' t provide a method to get the title of the currently displayed web page,
  • It just ignores all attempts to open links which are meant to open in new windows or tabs
  • It doesn' t allow accessing the HTML tree

WebKit itself provides provide classes for all these tasks, but all of them are private and not available on the iPhone.

Some of the alternative browsers which are available in the appstore just declare these limitations as feature (for example they advertise the inability to open new windows or tabs as "no anoying popup window "). this sounds great, but of course this doesn't make such browsers useful in the real world.

So what can we do to overcome these limitations of the uiwebview class? Can we (re) implement all the cool features of the WebKit framework which is available on the Mac on the iPhone as well without violating the iPhone SDK agreements with apple? Unfortunately, we can't. But we can implement attributes of the missing feature.

If you look at the available methods, there's only one, which wocould allow access to the content of the web page, and this is more or less the only way to get back the missing features. and this method is

- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;

This method is used to execute JavaScript code in the context of the current web page and get back a string as result. This means that we have to use JavaScript code to implement the features we need.

Let's start with something that is very easy. we implement methods to get the title and the URL of the currently displayed web page. we implement this as an objective C "category", so we don't need to subclass uiwebview:

File: mywebviewadditions. h

@interface UIWebView (MyWebViewAdditions)- (NSString*)title;- (NSURL*)url;@end

File: mywebviewadditions. m

#import "MyWebViewAdditions.h"@implementation UIWebView (MyWebViewAdditions)- (NSString*)title{    return [self stringByEvaluatingJavaScriptFromString:@"document.title"];}- (NSURL*)url{    NSString *urlString = [self stringByEvaluatingJavaScriptFromString:@"location.href"];    if (urlString) {        return [NSURL URLWithString:urlString];    } else {        return nil;    }}@end

What are we doing here?
From the Javascript's point of view a Web page is represented by the"Document"Object which has several properties. One of the properties is the"Title"Property which contains the title of the page. So with"Document. Title"We can access the title of the document within Javascript. And this is exactly what we need to pass as a parameter to the method" stringbyevaluatingjavascriptfromstring: "to get the document title.

For retreiving the URL we do something similar.

So whenever we need to get the title or URL of the web page that is displayed in a uiwebview object, we only need to call the "title" or "url" method:

NSString *title = [anyUIWebViewObject title];

The next limitation we may want to address is the inability to open links which wocould open in a new window. the WebKit on the Mac wocould just call a delegate method of the Host application to request that a new webview object is created for an URL request. the application wowould then create a new webview object and load the new page there. but on the iPhone the uiwebview doesn't support such a delegate method and so all attempts to open such a link are just ignored.

These links do usually look like this:

<a href="destination" target="_blank">Link Text</a>

The"Target"Attribute defines where the link will open. The value can be a name of a frame (if the web page has frames), the name of a window or some reserved target names like"_ Blank"(Opens a new window),"_ Self"(The window itself),"_ Parent"(The parent frame, if there are nested frames) and"_ Top"(The top-level or root frame, or identical to"_ Self"If the page doesn' t use frames ).

As a first step, we want to tap on a such a link in our iPhone app, and the link shoshould open like any other normal link in the same uiwebview object. what we need to do is simple: we need to find all links with a"Target"Attribute set to"_ Blank"And change its value to"_ Self". Then the uiwebview object will no longer ignore these links. to be able to modify all of the link targets we have to wait until the page has finished loading and the whole web page content is available. fortunately uiwebview provides the delegate Method

- (void)webViewDidFinishLoad:(UIWebView *)webView;

Which will be called when the web page has finished loading. so we have everything we need: We get notified when the page has loaded, and we know a way to access and modify the web page content (using "stringbyevaluating+criptfromstring:").

First we write our JavaScript code. because this will be a little bit more code than what was needed to get the document title, it's a good idea to create an extra file for our JavaScript code and then we add this file to the resources of our project in xcode:

File: modifylinktargets. JS:

function MyIPhoneApp_ModifyLinkTargets() {    var allLinks = document.getElementsByTagName('a');    if (allLinks) {        var i;        for (i=0; i<allLinks.length; i++) {            var link = allLinks[i];            var target = link.getAttribute('target');            if (target && target == '_blank') {                link.setAttribute('target','_self');            }        }    }}

What is this JavaScript function doing, when called?
It gets an array of all links ("A"Tags) and then loops through all of these tags, checks if there's a target attribute with the value"_ Blank". If this is the case it changes the value to"_ Self".

Note: There are other tags which can have a"Target"Attribute, like the"Form"Tag and the"Area"Tag. so you can use the" getelementsbytagname () "call to get these tags as well and modify their target attributes in the same way as I 've done this for the"A"Tag.

In our iPhone app we need to define a delegate for the uiwebview object and this delegate object will be called whenever the web page has finished loading. this is the method that is called in the delegate by the uiwebview object:

- (void)webViewDidFinishLoad:(UIWebView *)webView{    NSString *path = [[NSBundle mainBundle] pathForResource:@"ModifyLinkTargets" ofType:@"js"];    NSString *jsCode = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];    [webView stringByEvaluatingJavaScriptFromString:jsCode];    [webView stringByEvaluatingJavaScriptFromString:@"MyIPhoneApp_ModifyLinkTargets()"];}

What is this code doing?
At first the access path of the Javascript file we created before is retreived from the application bundle and we load the content of the file (the JavaScript code) into a string. then we execute/inject this code into the web page and finally we call out JavaScript function
Which is modifying the link targets.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.