WebKit on the iPhone(Part 2)



In the first part of this tutoril you've learned that you can use JavaScript code to get information about the web page and to modify links which world be normally ignored by UnibView
In the second part of the tutorial you'll learn how to open links(which are supposed to open in in a new window)in a new tab.On the iPhone you't open multip windows、so we have to use「tabs」instead.windows.soll.windows.sol.windows.
In part one we've written the JavaScript function「MyIPhone appuuModifyLinkTarggets()」which loops throuuggh alalalalalalalplacs the link taget“_blank”with“_self”.Thistheinininfefefefefefefefefefefefefefefefefefefefefefefefeeeeeeeeeeeeeeeeewiwiwiwiwiwiwiwiwiwiwiwiwiwiwiwiwiwiwiwiwiwiwiwiwiwiwiwiwiwith th th th th th th th th th th th th th th th th th thethetheaatttttttks in new tabs,we have to open a new タb ourselves and then open the link there.This can’t be directly done within the JavaScript code.So we have to find a way to pass the information aout the the link the link taget the the Objectititive the the the the abjjectititititititive the aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaIn order tomake it easury to recognize our modified URLs,we are creating the new URLs with a new custom URL scheme“newtab”.We just add this to the existing JavaScript function we’ve written the last partator.tor.tuial.
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');
                link.href = 'newtab:'+escape(link.href);
            }
        }
    }
}
The additional line
link.href = 'newtab:'+escape(link.href);
will take the original URL and escapes all the characters with a special meaning(like":"and"/")and put the new custom URL scheme"newtab"in front of it.The link URL"http://www.apple.com/」will be converted to「newtab:http%3 A/www.apple.com/」for example.
Within the Objective-C code of our ap,we have to implement the UnibView delegate method
- (BOOL)webView:(UIWebView *)view shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
This delegate method is caled whenever a link is tapped by the user.And the ap can check the URL and return YES or NO,wether it is OK to open URL or not.What we need to is to check if the URL If this is is the case we create a new tab with a new UUUUmibView oject and then open thethe ororinininininal URL in thisnenew UUUnib Vieoject.Finally we return No No No the rererererestststststthe dererererererereaate mestststststststststststststinininininininininininstststststststststststststststststststststststinininininininininininininininininininininininininininininininininininininininnd out that this delegate method is caled with an URL that was not modified,we just return YES,so the URL will open as expected.We know the URL was modified,if the URL uses the URL scheme"newtab"
- (BOOL)webView:(UIWebView *)view shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSURL *url = [request URL];
    if ([[url scheme] isEqualToString:@"newtab"]) {
        NSString *urlString = [[url resourceSpecifier] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        url = [NSURL URLWithString:urlString relativeToURL:[view url]];
        [self openNewTabWithURL:url];
        return NO;
    }
    return YES;
}
The.The.reourcleSpecifer.method of the NS URL object is returning evrything but the URL scheme,which isiseeexactlywhat we need to the ororororororinal URL.And because withinthe JavaScript code codededewewewe codededededewewewewewewes s s s s s s s s s s s codewewewewewewewee e e e e e e e eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeweweweweweweweweweweThe method「openNewTabWithURL:」is not shown here、but it is ovious what it is supposed to do:it creates a new tab with a new Unib View and opens the URL in the new tab.
In the above code you'll notice thisライン:
url = [NSURL URLWithString:urlString relativeToURL:[view url]];
We cal「view url」here(caling the method we’ve written in the first part of the tutoril)to get the base URL、in case we’ve received only a relative URL from the JavaScript code.For normlintworls.property of a link element will always return the absoliute URL.But when dealing with with windows or tabs which are opened using JavaScript code and not from within links,it is possible to receive to to receive only thelative forable
And now it’s time to explanin how new windows can be opened with JavaScript code、without any HTlinks.Manweb pages are dong this、oten for popup window with advertising baners、but also sometimetwent.
In JavaScript there’s the call
window.open(url,target,parameters)
Where“url”is the URL to open,“targt”is the target,simillar to the target atribute of HTML links and“parameters”ar paramters which tell the browser the location and size window and the front the with with the with with with windowson the iPhone with a target that is a new window,nothing will happen.This because the UnibView overject doesn't support new windows.So need to overwrite theオリジナリティ「window.open」caled.Our own code will then chchchecif the taget will open a new window.If thisisthe case,we create a new URL with the scheme“newtab”,likewe've dointhwith the links.And then wewealininininininininininininininininininininineeeeeexthethethethetheaaaaaaaaaaaaaaaaaathethethethethethethethethethethethethethethethethethethethethethethethethethethethethethethethethethethethethethethethethethethethethethethethethethererererereref".
function MyIPhoneApp_ModifyWindowOpen() {
    window.open =
            function(url,target,param) {
                if (url && url.length > 0) {
                    if (!target) target = "_blank";
                    if (target == '_blank') {
                        location.href = 'newtab:'+escape(url);
                    } else {
                        location.href = url;
                    }
                }
            }
}
Please note that this code makes certain assiumptions:The re areのHTML frame used in the web page and the only target names are“_blank”、“_self”、“_parent”、Dealwith frame
In the delegate method「webView DidFinish Load:」we just need to call the JavaScript function「MyIPhone eApple WindowOpen()」as well.So we add a new line of code:
- (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()"];
    [webView stringByEvaluatingJavaScriptFromString:@"MyIPhoneApp_ModifyWindowOpen()"];
}
Now,whenever a web page uses the JavaScript call「window.open()」,to open a page in a new window,the delegate method「webView:shuldStart Loadwirequest:navitionType:」is caled,jurewest west weewwitte.URL scheme when necessary,this atomuttically detected by the code we've written before.
What you’ve learned so far?You can write an iPhone ap where a web page loaded in UICWebView oject is able to open new tabs,regardless if is done usine HTML Link or via JavaScript using“window.open”The whole solution is more coplicated than on the Mac where the WebView oject is able to notify us about new windows or tabs have to be created.But even to use a mixture of Object Javant.
Final notes:
The re are still some details which are not covered by this tutorial.For example web pages can have「frame」and the tagets referenced by links and「window.open()」can also address thers frame.So you would need some additional code to check if a frame with the taget name exists.If there’s a frame with the taget name,then dot modify the link
Also「window.open()」will usualy return a reference to the newly created window oject so that the JavaScript code can access it later again.This can not be done the iPhone using the iPhone SDKBut fortunally、most web pages don’t need to access the new windows later、so this limitation is usualy not a big deal.
Posted in iPhone&iPod touch,Prograamming.
Tagged with Cocoa,Development,iPhone,WebKit.
53 comments
By Alexander–August 5,2009