NSString in UIWebview

后端 未结 2 1549
无人共我
无人共我 2020-11-29 03:07

I have an NSString and a webView in my project (Objective-C for iPhone), I have called index.html in webView and inside it I inserted my script (ja

2条回答
  •  庸人自扰
    2020-11-29 03:47

    When passing an NSString into a UIWebView (for use as a javascript String) you need to make sure to escape newlines as well as single/double quotes:

    NSString *html = @"
    Hello there
    "; 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];

    The reverse process is well described by @Michael-Kessler

提交回复
热议问题