我正在尝试从 UIWebView 中加载的本地 html 文件调用 javascript 函数
但它没有反应
看起来像这样
NSString *script=[NSString stringWithFormat:@"sample()"];
if (tekst.loading) {
NSLog(@"Loading");
} else {
NSLog(@"Fully loaded");
[tekst stringByEvaluatingJavaScriptFromString:script];
}
在 html 中
<head>
....
<script type='text/javascript'>
function sample() {
alert('Paznja');
}
</script>
...
</head>
最佳答案
在我看来,您好像没有在 UIWebView 上使用委托(delegate)。如果您设置一个委托(delegate)并将对 Javascript 的调用放入“- (void)webViewDidFinishLoad:(UIWebView *)webView”方法,它工作正常:
UIWebView *wv = [[UIWebView alloc] initWithFrame:CGRectMake(0.0, 0.0, 700.0, 700.0)];
[self.view addSubview:wv];
wv.delegate = self;
[wv loadHTMLString:@"<html><head><script type='text/javascript'>function sample() {alert('Paznja');}</script></head><body><h1>TEST</h1></body></html>" baseURL:nil];
[wv release];
在同一个类(class):
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[webView stringByEvaluatingJavaScriptFromString:@"sample()"];
}
当我运行这段代码时,警报消息工作正常。
关于javascript - stringByEvaluatingJavaScriptFromString 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6656544/