return value javascript UIWebView

前端 未结 2 1052
醉酒成梦
醉酒成梦 2021-01-02 09:26

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

On OS X the WebView method -stringByE

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-02 09:49

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

    The minimum code that worked for me:

    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];
    

    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.

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

提交回复
热议问题