Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the character encoding in UIWebView?

Tags:

Summary of the problem: When browsing non-English sites that does not explicitly specify the correct character encoding with UIWebView on the iOS, the page cannot be displayed correctly.

Detailed explanation: As the loadRequest: method in UIWebView will use the encoding specified in the charset header sent from the web server or the charset written in the HTML meta tag, and default to iso-8859-1 (well, I am not too sure about this) when charset is not specified, which cause non-English sites cannot display properly.

I have tried to Google for a way to change the charset that the UIWebView use, but the only way is to use the loadData:MIMEType:textEncodingName:baseURL: method to specify the encoding name.

However, it is not a good idea to use loadData:MIMEType:textEncodingName:baseURL: + NSURLConnection instead of loadRequest:, because UIWebView won't call the delegate method webView:shouldStartLoadWithRequest:navigationType: for frames, and even if we found a way to get notified when UIWebView load a frame, we cannot call loadData:MIMEType:textEncodingName:baseURL: to load the frame content, because it will load the frame as the outer page if we do that.

Besides, I have tried to use a javascript hack, but seems that property is read-only and cannot be changed.

[webView stringByEvaluatingJavaScriptFromString:@"document.characterSet='utf-8';"];   

Another workaround is inserting a meta tag to the HTML, and ask UIWebView to load the modified code, but the frame problem mentioned above also apply here.

<meta http-equiv="Content-Type" content="text/html;charset=utf-8"> 

Question: Is there any better solution that can change the character encoding in a loaded webpage in UIWebView, and handle frames properly?

like image 604
howanghk Avatar asked Feb 11 '11 19:02

howanghk


1 Answers

You can do this by manually loading the HTML, modifying it, and then loading the modified content into the UIWebView.

  • manually load the HTML from the page that doesn't include the meta tag, into a string (e.g. use NSURLConnection)
  • using string manipulation, insert your appropriate encoding meta tag into the manually loaded HTML
  • set the HTML in your web view to the modified string using loadHTMLString:

Now, this will work fine for a web page that contains no links. If it contains links, then you will find that after they click on a link, the new page will not have your modification in place. Therefore, you will need to manually intercept all of the clicks. Here's how you can do that:

  • Implement a UIWebView delegate
  • Implement the method webView:shouldStartLoadWithRequest:navigationType:
  • In your delegate method, load the URL manually and modify the content before setting it into the UIWebView, as above.
like image 102
Simon Woodside Avatar answered Sep 22 '22 18:09

Simon Woodside