简体   繁体   中英

UIWebView detect when javascript is loading a new page

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!

是:要捕获Javascript引发的页面加载,您应该在webView: shouldStartLoadWithRequest:navigationType:检查navigationType == UIWebViewNavigationTypeOther webView: shouldStartLoadWithRequest:navigationType:

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM