xcode stringByEvaluatingJavaScriptFromString 不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6656544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
stringByEvaluatingJavaScriptFromString does not work
提问by Vix
I am trying to call a javascript function from loaded local html file in UIWebView
but it deosn't respond
我正在尝试从加载的本地 html 文件中调用 javascript 函数,UIWebView
但它没有响应
it look like this
它看起来像这样
NSString *script=[NSString stringWithFormat:@"sample()"];
if (tekst.loading) {
NSLog(@"Loading");
} else {
NSLog(@"Fully loaded");
[tekst stringByEvaluatingJavaScriptFromString:script];
}
and in html
并在 html
<head>
....
<script type='text/javascript'>
function sample() {
alert('Paznja');
}
</script>
...
</head>
回答by joern
It looks to me as if you are not using a delegate on your UIWebView. If you set a delegate and put the call to the Javascript into the "- (void)webViewDidFinishLoad:(UIWebView *)webView " method, it works fine:
在我看来,您好像没有在 UIWebView 上使用委托。如果您设置一个委托并将对 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];
and in the same class:
并且在同一个班级:
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[webView stringByEvaluatingJavaScriptFromString:@"sample()"];
}
When I run this code, the alert message works fine.
当我运行此代码时,警报消息工作正常。
回答by Mike Pollard
Additional note, if you are expecting an object back from the javascript function rather than a string then do the following:
附加说明,如果您希望从 javascript 函数返回一个对象而不是字符串,请执行以下操作:
NSString *json = [self.webView stringByEvaluatingJavaScriptFromString:@"JSON.stringify(TestMethod())"];