0

I use PJAX to change pages on my site and for every new page I send a Response Header with a new a Page-Title header. This header contains can contain åäö, and IE outputs this incorrectly. In IE's Developer Tools I can see the Page-Title response without problem, but when I use document.title = ... to update the title it displays wrong.

My response header looks like this: Page-Title: Mårtensson

UTF8 is confirmed, I can see Content-Type: text/html; chartset=UTF-8 in both IE's and Chrome's Dev Tools.

This is how I update the title:

$.ajax({
    url: State.url,
    type: 'get',
    beforeSend: function(xhr){ 
        xhr.setRequestHeader('X-PJAX', true); 
    },
    success: function(resp, status, xhr) { 
        document.title = xhr.getResponseHeader('Page-Title');
        // other code
    }
});

This works in Chrome but in IE it outputs as MÃ¥rtensson. If I use decodeURIComponent(escape(document.title = xhr.getResponseHeader('Page-Title'))); it outputs fine in IE, but then in Chrome I get Uncaught URIError: URI malformed.

How can I get it to work in both browsers?


Solution

I fixed it by running htmlentities on the string before I output it as a response header. I then decode the string in javascript before I set it as title.

document.title = decodeEntities(xhr.getResponseHeader('Page-Title'));
Community
  • 1
  • 1
Marwelln
  • 28,492
  • 21
  • 93
  • 117

1 Answers1

0

you can check RFC 5987 that specifically deals with this issue. Basically, keep in mind that if you use UTF-8 characters in a HTTP header field, you are on your own and different browsers will have different behavior.

If you really need to use a header for this, you should use some kind of escaping (server side) and unescaping (client side) to make your title fit into the ISO-8859-1 charset.

Community
  • 1
  • 1
Jerome WAGNER
  • 21,986
  • 8
  • 62
  • 77
  • There may be also a problem with displaying non-ASCII characters in `document.title`, no matter where data came from. – kirilloid Oct 31 '13 at 11:03
  • Thanks. I now run `htmlentities` on the string before i output it to the header and then decode it with javascript as http://stackoverflow.com/a/9609450/397195 described. – Marwelln Oct 31 '13 at 11:18