【问题标题】:UIWebView respond to Javascript callsUIWebView 响应 Javascript 调用
【发布时间】:2011-09-25 09:28:02
【问题描述】:

如何像 Mobile Safari 那样拦截诸如 window.open 之类的 Javascript 调用?我没有看到任何关于此的列表,但它一定有可能吗?

以前有人做过吗?

【问题讨论】:

  • UIWebView 中的这个方法: - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script ?
  • 错误没有?那就是注入JavaScript。如果一个网站调用window.open,我需要拦截它。

标签: iphone objective-c uiwebview


【解决方案1】:

当页面完成加载 (webViewDidFinishLoad:) 时,注入一个 window.open 覆盖。当然,它不适用于在页面加载期间调用的 window.open。 然后使用自定义方案来回调您的目标 C 代码。
[编辑] 好的,我已经测试过了。现在可以了。
创建一个新的“基于视图”的项目,并使用 IB 在 vi​​ewcontroller 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/

【讨论】:

  • 我知道它有效,我在我的应用程序中使用它来捕获谷歌地图标记。请参阅我编辑的答案。
  • 虽然这并没有显示 URL - 所以我编辑了你的答案,所以它可以正确返回 URL :) 现在可以使用了!
  • 也适用于关闭窗口
  • 如果用户的javascript简单地调用delete window.open怎么办?它可以撤消您的覆盖!
猜你喜欢
  • 2011-06-13
  • 2012-02-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多