gpt4 book ai didi

iphone - UIWebView 响应 Javascript 调用

转载 作者:搜寻专家 更新时间:2023-10-30 19:56:49 25 4
gpt4 key购买 nike

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

有人做过吗?

最佳答案

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

关于iphone - UIWebView 响应 Javascript 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6525191/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com