I am new to chrome extension development. I want to use extension to change page charset, like chrome setting>>tools>>charset. And I had seen the document with chrome extension about chrome.contentSetting1. but I had not found how to change page charset.
Asked
Active
Viewed 1,228 times
5
-
Is your extension released? – e9t Oct 05 '15 at 15:44
1 Answers
4
Yes. Via how to change response header in Chrome:
chrome.webRequest.onHeadersReceived.addListener(function(details){
for(var i = 0; i < details.responseHeaders.length; ++i)
if(details.responseHeaders[i].name.toLowerCase() == 'content-type')
details.responseHeaders[i].value = 'text/html; charset=shift-jis';
return {responseHeaders:details.responseHeaders};
}, {urls: ['https://www.google.com/*']}, ['blocking', 'responseHeaders']);
If you want to update the charset on pageload, you will need a chrome.webRequest.onCompleted.addListener
that updates meta tags in the document <head>
. This cannot be a called pragmatically via chrome.tabs.executeScript()
as the document is rendered with the specified charset.
chrome.webRequest.onCompleted.addListener(function(details){
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.executeScript(null, {allFrames:true,code:"document.getElementsByTagName('meta')[0].setAttribute('content', 'text/html; charset=UTF-8');"});
});
}, {urls: ['http://google.com/']});
Either of these functions go in your background.js
file that is loaded in manifest.json
:
{
"manifest_version": 2,
// name,description,version...
"background": {
"scripts": ["background.js"],
"persistent": true,
//"matches": ["https://google.com/"]
},
"permissions": [
"tabs",
"webRequest",
"webRequestBlocking"
]
}
Once a page is initialized and rendered, there is no way to change the charset. document.charset
is readonly, and triggering a re-render does not appear to affect the document charset, even if altered.
-
1This is a solution to change it _before_ the page loads; question is still open for an already-loaded page. – Xan May 16 '15 at 08:44
-
So I guess the best approximation to a post-load change is "Activate webRequest listener, reload, deactivate listener". – Xan May 18 '15 at 23:04
-
-
Yeah, except that one can never assume that reloading a URL does not have side-effects. Users must be aware of it. – Xan May 18 '15 at 23:37