Monday, March 19, 2012

WebView.loadData() problem with load html and special character.

If you try to load HTML directly from a String into a WebView, including
any of the characters ' # or % in the HTML String (specifically, the CDATA
sections) will cause the HTML page to be truncated (in the case of ' and #)
or possibly locally corrupted (in the case of %) at that point. These
characters are not URL-safe, and WebView.loadData(htmlString, mimeType,
encoding) encodes the HTML string in a "data://" URL before passing it to
WebKit.

I have to have the following workaround in my code:
int len = html.length();
StringBuilder buf = new StringBuilder(len + 100);
for (int i = 0; i < len; i++) {
char chr = html.charAt(i);
switch (chr) {
case '%':
buf.append("%25");
break;
case '\'':
buf.append("%27");
break;
case '#':
buf.append("%23");
break;
default:
buf.append(chr);
}
}
String fixedHTML = buf.toString();
mResultsView.loadData(fixedHTML, "text/html", "utf8");

This is a pretty serious bug... not even the escape char % is being escaped??

No comments:

Post a Comment