如何使用encoding.min.js API通过GM_xmlhttpRequest将httprequest结果转换为EUC-JP?

问题描述 投票:0回答:1

我从字符集为 EUC-JP 的 URL 获取 httprequest 结果,显示乱码。

我尝试获取Buffer结果并将其转换为EUC-JP,但结果仍然显示乱码。

如何获取UTF8结果?

// ==UserScript==
// @name         New Userscript
// @namespace    http://tampermonkey.net/
// @version      2024-08-25
// @description  try to take over the world!
// @author       You
// @match        http://*/*
// @icon         data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
// @grant        none
// @require      https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.min.js
// @require      https://cdn.jsdelivr.net/npm/[email protected]/encoding.min.js

// ==/UserScript==
    function convertBufferToEucJp(buffer) {
        // Convert buffer to Uint8Array
        const uint8Array = new Uint8Array(buffer);

        // Convert Uint8Array to string with UTF-8 encoding (assuming the buffer is UTF-8)
        const utf8String = new TextDecoder("utf-8").decode(uint8Array);

        // Convert UTF-8 string to EUC-JP
        const eucJpString = Encoding.convert(utf8String, {
            to: 'EUCJP',
            from: 'UTF8'
        });

        return eucJpString;
    }

    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", // Get response as ArrayBuffer
        onload: function(response) {
            if (response.status >= 200 && response.status < 300) {
                // Convert ArrayBuffer to EUC-JP string
                const eucJpString = convertBufferToEucJp(response.response);

                // Do something with the EUC-JP string
                console.log(eucJpString);
            } else {
                console.error("Error fetching data:", response.status);
            }
        },
        onerror: function(error) {
            console.error("Request error:", error);
        },
    });
javascript node.js character-encoding xmlhttprequest httprequest
1个回答
0
投票

将ArrayBuffer结果从EUCJP转换为UNICODE,显示正常。

© www.soinside.com 2019 - 2024. All rights reserved.