简体   繁体   English

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

[英]Loading large HTML string into UIWebView using javascript

Usually, when I want to load an HTML string into a webview using javascript, I use something like this... 通常,当我想使用javascript将HTML字符串加载到webview中时,我使用这样的东西......

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

While this appears to work well for small strings, it has no effect when the string it relatively large. 虽然这似乎适用于小字符串,但当字符串相对较大时它没有效果。 Apparently, there is a length limit. 显然,有一个长度限制。

So, my question here is, if anyone knows of a way to load a large string into a UIWebView without having to reload the webview? 所以,我的问题是,如果有人知道如何在不重新加载webview的情况下将大字符串加载到UIWebView中?

UPDATE: To be a little clear, in my case here, the webview is already loaded, I just want to replace it's content without having to reload it, mainly because reloading the webview is not fast enough for my use. 更新:有点清楚,在我的情况下,webview已经加载,我只想替换它的内容而不必重新加载它,主要是因为重新加载webview不够快我的使用。

I'm able to pass extremely long strings with stringByEvaluatingJavaScriptFromString , so I doubt that is the problem. 我能用stringByEvaluatingJavaScriptFromString传递非常长的字符串,所以我怀疑这是问题所在。 (Note I'm writing for osx, not ios which might make a difference) (注意我写的是osx,而不是可能有所不同的ios)

It might be that your are not escaping the html correctly so it's being passed as invalid javascript, which could cause nothing to happen. 可能是你没有正确地转义html所以它被作为无效的javascript传递,这可能不会发生任何事情。 I'm doing the following to a string before passing it to 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 ];

I don't know if all of that is necessary or either it could be written more succinctly (I'm very new to objective c), but it seems to work fine for me. 我不知道是否所有这些都是必要的,或者它可以更简洁地写出来(我对目标c非常新),但它似乎对我来说很好。

If the HTML is in a file, you could do this: 如果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]];  

If you literally want to load an HTML string, try this: 如果你真的想加载一个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