fc2ブログ

今どきの文字コード変換

CATEGORY未分類
EUC で URI エンコードされた文字列を javascript で使いたい という件。 今どきは、TextDecoder を使うらしい。

fetch と組み合わせると、UTF-8 じゃないページでもデータを扱えるということらしい。

async function fetch_and_decode(url) {
    const response = await fetch(url, {credentials: "include", redirect: "follow"});
    const responseURL = new URL(response.url);
    
    const contentType = response.headers.get("Content-Type");
    if (contentType === null) {
        throw new Error(`Content-Type Error: ${contentType}`);
    }
    const mimeType = new MIMEType(contentType);
    if (!mimeType.isHTML() && mimeType.essence !== "application/xhtml+xml") {
        throw new Error(`Content-Type Error: ${contentType}`);
    }
    
    const ab = await response.arrayBuffer();
    const charset = mimeType.parameters.get("charset") || document.characterSet;
    const textDecoder = new TextDecoder(charset);
    const responseText = textDecoder.decode(ab);
    
    return {responseURL, responseText};
}
※CORS の問題はあるとしても。
関連記事
スポンサーサイト



javascript

0 Comments

Leave a comment