UIWebView detect when javascript is loading a new

2019-06-05 06:05发布

I have a UIWebView and I want ALL links to open on a new page.

I have this code to detect when a user clicks a link and open that link on a new page:

- (BOOL) webView:(UIWebView*)webView shouldStartLoadWithRequest: (NSURLRequest*) request navigationType: (UIWebViewNavigationType)navigationType {


//If the user clicked a link don't load it in this webview
if (navigationType == UIWebViewNavigationTypeLinkClicked) {


        NSURL* URLToGoTo = [request URL];
        self.fullWebView.url = URLToGoTo;
        [self.navigationController pushViewController:fullWebView animated:YES];
        return NO;
}
//Else this is the webview being loaded for the first time, let it load.
return YES;

The problem is some website use javascript to open links like this:

win = window.open("/magic/card.asp?name="+cardname+"&set="+set+"&border="+border, windowName, params);

if (!win.opener) 
{
    win.opener = window;
}

Unfortunately these types of links do not have the UIWebViewNavigationTypeLinkClicked property and will open in the same window of my UIWebView.

I tried looking at the scheme property of the URL to see if it were "javascript" but it looks identical to the URL used by regular links.

Can anyone think of a way to detect when a webpage is being opened by a javascript function?

I suppose worst case scenario I can use a boolean to determine if this is the first time the my UIWebView is being loaded and load all subsequent links in a new page, but there must be a better solution

Thanks!

2条回答
霸刀☆藐视天下
2楼-- · 2019-06-05 06:17

Yes: to catch the Javascript-induced page loads you should check for navigationType == UIWebViewNavigationTypeOther in webView: shouldStartLoadWithRequest:navigationType:.

查看更多
地球回转人心会变
3楼-- · 2019-06-05 06:39

A navigationType of UIWebViewNavigationTypeOther will also include background page loads such as analytics, which I presume you don't want to load externally.

To detect only page navigation, you need to compare the [request URL] to the [request mainDocumentURL]:

- (BOOL)webView:(UIWebView *)view shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)type
{
    if ([[request URL] isEqual:[request mainDocumentURL]])
    {
        [[UIApplication sharedApplication] openURL:[request URL]];
        return NO;
    }
    else
    {       
        return YES;
    }
}
查看更多
登录 后发表回答