如何用GM_xmlhttpRequest结合encoding.min.js将EUC-JP请求结果转UTF-8?
解决GM_xmlhttpRequest请求EUC-JP编码URL的乱码问题
你的代码核心错误在于先将EUC-JP编码的字节用UTF-8解码,这会直接破坏原始字节数据,导致后续的编码转换完全失效。正确的做法是直接用EUC-JP编码解码原始ArrayBuffer,得到正确的文本后,JS会自动处理为内部的UTF-16格式(也就是你需要的可正常显示的字符串)。
方案一:使用原生TextDecoder直接解码(推荐)
现代浏览器的TextDecoder原生支持EUC-JP编码,直接用它解码ArrayBuffer即可:
// ==UserScript== // @name 解决EUC-JP编码乱码问题 // @namespace http://tampermonkey.net/ // @version 1.0 // @description 正确获取EUC-JP编码的网页内容 // @author You // @match http://*/* // @icon data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== // @grant GM_xmlhttpRequest // 必须授权才能使用GM_xmlhttpRequest // ==/UserScript== GM_xmlhttpRequest({ method: "GET", url: "https://seesaawiki.jp/av_video/d/%c6%e1%b2%ec%ba%ea%a4%e6%a4%ad%a4%cd", responseType: "arraybuffer", onload: function(response) { if (response.status >= 200 && response.status < 300) { // 直接用EUC-JP解码ArrayBuffer const decoder = new TextDecoder("EUC-JP"); const correctString = decoder.decode(response.response); console.log(correctString); // 此时correctString是可正常显示的字符串,可直接使用 } else { console.error("请求失败:", response.status); } }, onerror: function(error) { console.error("请求错误:", error); }, });
方案二:使用encoding-japanese库处理
如果你需要兼容老旧环境,可继续使用encoding-japanese库,但要注意正确处理字节流:
// ==UserScript== // @name 解决EUC-JP编码乱码问题 // @namespace http://tampermonkey.net/ // @version 1.0 // @description 正确获取EUC-JP编码的网页内容 // @author You // @match http://*/* // @icon data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw== // @grant GM_xmlhttpRequest // @require https://cdn.jsdelivr.net/npm/encoding-japanese@2.2.0/encoding.min.js // ==/UserScript== GM_xmlhttpRequest({ method: "GET", url: "https://seesaawiki.jp/av_video/d/%c6%e1%b2%ec%ba%ea%a4%e6%a4%ad%a4%cd", responseType: "arraybuffer", onload: function(response) { if (response.status >= 200 && response.status < 300) { // 将ArrayBuffer转为Uint8Array const uint8Array = new Uint8Array(response.response); // 直接从EUC-JP字节解码为JS字符串(内部为UTF-16) const correctString = Encoding.convert(uint8Array, { to: 'UNICODE', from: 'EUCJP' }); console.log(correctString); } else { console.error("请求失败:", response.status); } }, onerror: function(error) { console.error("请求错误:", error); }, });
关键注意点
- 必须在
@grant中声明GM_xmlhttpRequest,否则无法调用该API - 不要对EUC-JP字节做UTF-8解码,直接用目标编码解码原始字节流
- JS字符串内部默认是UTF-16格式,所以解码后的字符串无需再转UTF-8,直接即可正常显示
内容的提问来源于stack exchange,提问作者lyscop
相关产品推荐
相关产品推荐

