UIWebview中的NSString

IT技术 javascript iphone objective-c uiwebview uiwebviewdelegate
2021-03-14 14:34:14

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

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

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

2个回答

将字符串发送到网络视图:

[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';
反之亦然?:-)
2021-04-25 14:34:14

将 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 很好地描述了相反的过程