簡體   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