3

How can I intercept Javascript calls such as window.open as Mobile Safari does? I haven't seen anything listed about this, but it must be possible somehow?

Has anyone done this before?

Phillip Senn
  • 46,771
  • 90
  • 257
  • 373
Pripyat
  • 2,937
  • 2
  • 35
  • 69
  • This method in UIWebView: - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script ? – onnoweb Jun 29 '11 at 20:14
  • Err no? That's injecting JavaScript. If a website calls window.open, I need to intercept that. – Pripyat Jun 29 '11 at 20:34

1 Answers1

8

When the page is finished loaded (webViewDidFinishLoad:), inject a window.open override. Of course it will not work for window.open which are called during page load. Then use a custom scheme to callback your objective C code.
[EDIT] OK I have tested it. Now it works.
Create a new "view based" project and add a webview in the viewcontroller xib 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

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

The log

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/
Pripyat
  • 2,937
  • 2
  • 35
  • 69
FKDev
  • 2,266
  • 1
  • 20
  • 23