UIWebView响应Javascript调用 [英] UIWebView respond to Javascript calls

查看:63
本文介绍了UIWebView响应Javascript调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

当页面是完成加载(webViewDidFinishLoad :),注入一个window.open覆盖。当然,它不适用于在页面加载期间调用的window.open。
然后使用自定义方案回调您的目标C代码。

好的我已经测试过了。现在它可以工作。

创建一个新的基于视图的项目,并使用IB在viewcontroller xib中添加一个webview。

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.
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

Javascript:

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

日志

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/

这篇关于UIWebView响应Javascript调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆