UIWebView Answers Javascript Calls

How can I intercept Javascript calls like window.open , how does Mobile Safari do it? I have not seen anything on this list, but is it possible somehow?

Has anyone done this before?

+2
source share
1 answer

When the page is loaded (webViewDidFinishLoad :), insert an override of window.open. Of course, this will not work for window.open, which is called at page load time. Then use a custom schema to call back your object code C. [EDIT] OK I tested it. Now it works.
Create a new project based on the view and add the webview to the xib viewcontroller using IB.

 @implementation todel2ViewController // Implement viewDidLoad to do additional setup after loading the view, typically from a nib. - (void)viewDidLoad { [super viewDidLoad]; NSString* page = @"<html><head></head><body><div onclick='javascript:window.open(\"http://www.google.com\");'>this is a test<br/>dfsfsdfsdfsdfdsfs</div></body></html>"; [self.view loadHTMLString:page baseURL:[NSURL URLWithString:@""]]; } - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSString* urlString = [[request URL ] absoluteString ]; NSLog(@"shouldStartLoadWithRequest navigationType=%d", navigationType); NSLog(@"%@", urlString); if ([[[request URL] scheme] isEqualToString:@"myappscheme"] == YES) { //do something NSLog(@"it works"); } return YES; } - (void)webViewDidFinishLoad:(UIWebView *)webView { //Override Window NSString*override = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"NewWindow" ofType:@"js"] encoding:4 error:nil]; [self.view stringByEvaluatingJavaScriptFromString:override]; } @end 

Javascript:

 var open_ = window.open; window.open = function(url, name, properties) { var prefix = 'csmobile://'; var address = url; open_(prefix + address); return open_(url, name, properties); }; 

Journal

 2011-07-05 14:17:04.383 todel2[31038:207] shouldStartLoadWithRequest navigationType=5 2011-07-05 14:17:04.383 todel2[31038:207] myappscheme:it%20works 2011-07-05 14:17:04.384 todel2[31038:207] it works 2011-07-05 14:17:04.386 todel2[31038:207] shouldStartLoadWithRequest navigationType=5 2011-07-05 14:17:04.386 todel2[31038:207] http://www.google.com/ 
+7
source

Source: https://habr.com/ru/post/902703/


All Articles