返回值javascript UIWebView [英] return value javascript UIWebView

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

问题描述

我正在尝试使用iPhone SDK获取javascript函数的返回值(例如: returnhello)。

i'm trying to get the return value of a javascript function(for example: return "hello") with iPhone SDK.

在OS X上,WebView方法 -stringByEvaluatingJavaScriptFromString 返回包含js函数返回值的NSString,但在iPhone上没有返回任何值。

On OS X the WebView method -stringByEvaluatingJavaScriptFromString returns a NSString containing the js function return value, but on the iPhone no value is returned.

我该如何解决这个问题?

How can I solve this?

我找到了一个私有的UIWebViewDelegate方法

I found a private UIWebViewDelegate method

- (void)webView:(id)fp8 runJavaScriptAlertPanelWithMessage:(id)fp12 initiatedByFrame:(id)fp16

$ j
$ b

在js脚本中使用alert()函数时调用。所以我可以通过调用 alert(myReturValue)获得返回值。

invoked when the alert() function is used in the js script. So I can get the "return" value just by calling alert(myReturValue).

这不能解决我的问题,因为我在公共SDK中需要一些东西。

That doesn't solve my problem, because I need something in the public SDK.

推荐答案

返回字符串是最后一个Javascript语句的结果。 返回放在它前面!

The return string is the result of the last Javascript statement. Do not put return in front of it!

适用的最小代码我:

UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
[self.view addSubview:webView];
NSString *result = [webView stringByEvaluatingJavaScriptFromString:
                    @"function f(){ return \"hello\"; } f();"];
NSLog(@"result: '%@'", result); // 'hello'
[webView release];

所以我必须添加 UIWebView * 到视图(否则它会在之后崩溃),但不必在webview中加载任何内容。

So I had to add the UIWebView* to a view (otherwise it would crash afterwards), but didn't have to load anything into the webview.

请注意,最后一个语句只是 f(); ,因此返回的字符串将包含 f()的评估结果。

Notice that the last statement is just "f();", so the returned string will contain the result of the evaluation of f().

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

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