繁体   English   中英

使用javascript将大型HTML字符串加载到UIWebView中

[英]Loading large HTML string into UIWebView using javascript

通常,当我想使用javascript将HTML字符串加载到webview中时,我使用这样的东西......

NSString *htmlString = @"HTML String";
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"document.getElementById('elementid').innerHTML = \"%@\";", htmlString]];

虽然这似乎适用于小字符串,但当字符串相对较大时它没有效果。 显然,有一个长度限制。

所以,我的问题是,如果有人知道如何在不重新加载webview的情况下将大字符串加载到UIWebView中?

更新:有点清楚,在我的情况下,webview已经加载,我只想替换它的内容而不必重新加载它,主要是因为重新加载webview不够快我的使用。

我能用stringByEvaluatingJavaScriptFromString传递非常长的字符串,所以我怀疑这是问题所在。 (注意我写的是osx,而不是可能有所不同的ios)

可能是你没有正确地转义html所以它被作为无效的javascript传递,这可能不会发生任何事情。 在将其传递给javascript之前,我正在对字符串执行以下操作:

content = [content stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
content = [content stringByReplacingOccurrencesOfString:@"\n" withString:@"\\n"];
content = [content stringByReplacingOccurrencesOfString:@"\r" withString:@""];
NSString *js = [NSString stringWithFormat:@"set_content(\"%@\")", content];
[ web_view stringByEvaluatingJavaScriptFromString: js ];

我不知道是否所有这些都是必要的,或者它可以更简洁地写出来(我对目标c非常新),但它似乎对我来说很好。

如果HTML在文件中,您可以这样做:

NSString *path = [[NSBundle mainBundle] pathForResource: @"MyHTML" ofType: @"html"];
NSData *fileData = [NSData dataWithContentsOfFile: path];
[webView loadData: fileData MIMEType: @"text/html" textEncodingName: @"UTF-8" baseURL: [NSURL fileURLWithPath: path]];  

如果你真的想加载一个HTML字符串,试试这个:

NSString *embedHTML = @"<html><head></head><body><p>Hello World</p></body></html>";
[webView loadHTMLString: embedHTML baseURL: nil]; 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM