I'm developing iOS hybrid app coded by Objective-C. I want to catch 'window.open' events in UIWebView. I found this code.
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
if (navigationType == UIWebViewNavigationTypeLinkClicked ){
NSLog(@"opening link");
return NO;
}
....
...
return YES;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSString * test = [webView stringByEvaluatingJavaScriptFromString:@"window.open = function (open) { return function (url, name, features) { window.location.href = url; return window; }; } (window.open);"];
//
NSLog(@"test:%@", test); << always print blank
....
...
..
}
info.plist
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
But it catches not only 'window.open' but other link events. Some answers suggest to use 'stringByEvaluatingJavaScriptFromString', but I didn't understand.
Could you explain it for beginners to understand easily? I just want to catch 'window.open' event in UIWebView.
You need to use following code to detect window opening:
[webView stringByEvaluatingJavaScriptFromString:@"window.open = function (open) { return function (url, name, features) { window.location.href = url; return window; }; } (window.open);"];
Try to put above code below delegate method:
- (void)webViewDidFinishLoad:(UIWebView *)webView {}
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.