UIWebView响应Javascript调用

时间:2011-06-29 18:02:41

标签: iphone objective-c uiwebview

如何像移动Safari一样拦截window.open等Javascript调用?我没有看到任何关于此的列表,但它必须以某种方式可能吗?

以前有人这样做过吗?

1 个答案:

答案 0 :(得分:8)

当页面加载完毕后(webViewDidFinishLoad :),注入一个window.open覆盖。当然,它不适用于在页面加载期间调用的window.open。 然后使用自定义方案回调您的目标C代码 [编辑]好的我已经测试过了。现在它起作用。
创建一个新的“基于视图”项目,并使用IB在viewcontroller xib中添加webview。

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

日志

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/