Skip to content

Instantly share code, notes, and snippets.

@xiaokaike
Created October 29, 2018 02:48
Show Gist options
  • Save xiaokaike/281e5dfd2d5cd3e99e08e019965c5621 to your computer and use it in GitHub Desktop.
Save xiaokaike/281e5dfd2d5cd3e99e08e019965c5621 to your computer and use it in GitHub Desktop.
chrome-wechat-decode
/**
* 修复微信编码问题
*/
// MIME types to work on
const TARGET_MIME_TYPE = [
/^text\/[\w-.]+/i,
/^application\/json/i,
/^application\/(x-)?javascript/i,
/^application\/(xhtml+)?xml/i,
];
const TEXT_CODING_MAP = {
//name --> [language, code] map
default: ['Use_page_default'],
'utf-8': ['Unicode', 'UTF-8'],
'utf-16le': ['Unicode', 'UTF-16LE'],
};
const GLOBAL_SITE2CODE = {
'https://wx.qq.com/*': 'utf-8',
'https://wx2.qq.com/*': 'utf-8',
};
//extract site url pattern from page url
//this pattern servers as index for site-->code map, which is saved in local storage
function extractSiteUrlPattern(url) {
if (typeof url !== 'string') {
return 'Newtab';
}
const fragments = url.split('/').slice(0, 3);
return `${fragments.join('/')}/*`;
}
function findMatchedMime(header) {
for (let i = 0; i < TARGET_MIME_TYPE.length; i += 1) {
const result = header.match(TARGET_MIME_TYPE[i]);
if (result) {
return result[0];
}
}
return null;
}
function onHeadersReceivedHandler(details) {
const urlPattern = extractSiteUrlPattern(details.url);
if (GLOBAL_SITE2CODE[urlPattern]) {
let isTypeHeaderFound = false; // default value, to be updated later
const myCode = GLOBAL_SITE2CODE[urlPattern];
const myContentType = `text/html; charset=${myCode}`; // default content type
const headers = details.responseHeaders;
const newHeaders = headers.map(item => {
if (item.name.toLowerCase() === 'content-type') {
isTypeHeaderFound = true;
const matched = findMatchedMime(item.value.toLowerCase().trim());
if (matched && TEXT_CODING_MAP[myCode]) {
const value = `${matched}; charset=${myCode}`;
// for test
// console.log(
// `change header coding to ${myCode}, url =${
// details.url
// }, value = ${value}`
// );
return {
...item,
value,
};
}
//not a target MIME, do nothing
//console.log("non-target content-type found: " + header.value);
return item;
}
return item;
});
if (!isTypeHeaderFound) {
newHeaders.push({
name: 'content-type',
value: myContentType,
});
//console.log("Add coding header " + my_code + " for url =" + details.url);
}
return { responseHeaders: newHeaders };
}
return {};
}
chrome.webRequest.onHeadersReceived.addListener(
onHeadersReceivedHandler,
{
urls: ['<all_urls>'],
},
['blocking', 'responseHeaders']
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment