13

我的NSString项目中有一个 webView(iPhone 的 Objective-C),我调用index.html了 webView 并在其中插入了我的脚本(javascript)。

如何在我的脚本中将 NSString 作为 var 传递,反之亦然?

这是一个例子,但我不是很明白。

4

2 回答 2

30

将字符串发送到 Web 视图:

[webView stringByEvaluatingJavaScriptFromString:@"YOUR_JS_CODE_GOES_HERE"];

将字符串从 Web 视图发送到 Obj-C:

声明你实现了 UIWebViewDelegate 协议(在 .h 文件中):

@interface MyViewController : UIViewController <UIWebViewDelegate> {

    // your class members

}

// declarations of your properties and methods

@end

在 Objective-C 中(在 .m 文件中):

// right after creating the web view
webView.delegate = self;

在 Objective-C(在 .m 文件中)也是:

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSString *url = [[request URL] absoluteString];

    static NSString *urlPrefix = @"myApp://";

    if ([url hasPrefix:urlPrefix]) {
        NSString *paramsString = [url substringFromIndex:[urlPrefix length]];
        NSArray *paramsArray = [paramsString componentsSeparatedByString:@"&"];
        int paramsAmount = [paramsArray count];

        for (int i = 0; i < paramsAmount; i++) {
            NSArray *keyValuePair = [[paramsArray objectAtIndex:i] componentsSeparatedByString:@"="];
            NSString *key = [keyValuePair objectAtIndex:0];
            NSString *value = nil;
            if ([keyValuePair count] > 1) {
                value = [keyValuePair objectAtIndex:1];
            }

            if (key && [key length] > 0) {
                if (value && [value length] > 0) {
                    if ([key isEqualToString:@"param"]) {
                        // Use the index...
                    }
                }
            }
        }

        return NO;
    }
    else {
        return YES;
    }
}

JS内部:

location.href = 'myApp://param=10';
于 2010-09-18T17:11:20.120 回答
0

将 NSString 传递给 UIWebView(用作 javascript 字符串)时,您需要确保转义换行符以及单/双引号:

NSString *html = @"<div id='my-div'>Hello there</div>";

html = [html stringByReplacingOccurrencesOfString:@"\'" withString:@"\\\'"];
html = [html stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
html = [html stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"];
html = [html stringByReplacingOccurrencesOfString:@"\r" withString:@""];

NSString *javaScript = [NSString stringWithFormat:@"injectSomeHtml('%@');", html];
[_webView stringByEvaluatingJavaScriptFromString:javaScript];

@Michael-Kessler 很好地描述了相反的过程

于 2014-04-02T12:16:01.197 回答