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!
Yes: to catch the Javascript-induced page loads you should check for
navigationType == UIWebViewNavigationTypeOther
inwebView: shouldStartLoadWithRequest:navigationType:
.A
navigationType
ofUIWebViewNavigationTypeOther
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]
: