UIWebView detect when javascript is loading a new page

大兔子大兔子 提交于 2019-12-08 09:10:16

问题


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!


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/9403810/uiwebview-detect-when-javascript-is-loading-a-new-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!