Front-end implementation of GBK and GB2312 encoding and decoding of strings (summary)

Front-end implementation of GBK and GB2312 encoding and decoding of strings (summary)

Preface

When developing a project, I encountered a rather tricky problem. The product requires the search term in the browser address bar to be obtained from the browser for judgment. We generally use the UTF-8 encoding format, but Baidu and Google both use GBK encoding when encoding search terms. This results in decoding failure. So I looked for a solution online and finally found a method sorted out by a senior. The problem was solved through iframe, so I would like to summarize it here for my own future use. I also hope it can help more people. Finally, I will put a link to the front-end article.

1. Encoding (support GBK and GB2312)

To avoid trouble, we can set the form's request page as the current page and put the callback function at the front of the page JS. In this way, when this page has a parent page and __encode__iframe__callback__ is defined, the callback can be executed directly and the window can be closed:

if (parent.__encode__iframe__callback__) { // Determine whether the current page is a child window parent.__encode__iframe__callback__(location.search.split('=')[1]);
    //Close the current subwindow directly window.close();
}
function GBKEncode(str, charset, callback) {
    //Create a form and encode it using accept-charset
    var form = document.createElement('form');
    form.method = 'get';
    form.style.display = 'none';
    form.acceptCharset = charset;
    if (document.all) {
        //If it is IE, then call the document.charset method window.oldCharset = document.charset;
        document.charset = charset;
    }
    var input = document.createElement('input');
    input.type = 'hidden';
    input.name = 'str';
    input.value = str;
    form.appendChild(input);
    form.target = '__encode__iframe__'; //Specify the iframe of the target submitted
    document.body.appendChild(form);
    //Hide the iframe to intercept the submitted string if (!window['__encode__iframe__']) {
        var iframe;
        iframe = document.createElement('iframe');
        iframe.setAttribute('name', '__encode__iframe__');
        iframe.style.display = 'none';
        iframe.width = "0";
        iframe.height = "0";
        iframe.scrolling = "no";
        iframe.allowtransparency = "true";
        iframe.frameborder = "0";
        iframe.src = 'about:blank'; // Set to blank document.body.appendChild(iframe);
    }
    //
    window.__encode__iframe__callback__ = function (str) {
        callback(str);
        if (document.all) {
            document.charset = window.oldCharset;
        }
    }
    //Set the address of the callback encoding page. Here the user needs to modify form.action = window.location.href;
    form.submit();
    setTimeout(function () {
        form.parentNode.removeChild(form);
        iframe.parentNode.removeChild(iframe);
    }, 1000) // Remove the node after 0.5 seconds }
GBKEncode('characters to be encoded', 'gb2312', callback); // test // promise encapsulation var encode = function encode(str) {
    var charset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'gbk';
    return new Promise(function (resolve, reject) {
        try {
            _encode(str, charset, function (data) {
                resolve(data);
            });
        } catch (e) {
            resolve('Character encoding error.', e.toString());
        }
    });
};

2. Decoding (support GBK, GB2312, Base64)

function randomId() {
    var text = "";
    var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    for (var i = 0; i < 5; i++) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    }return text;
}

function _decode(str, charset, callback) {
    var script = document.createElement('script');
    var id = randomId(); // Generate a unique ID to prevent conflicts script.id = '_urlDecodeFn_' + id;
    window['_urlDecodeFn_' + id] = callback;
    var src = 'data:text/javascript;charset=' + charset + (',_urlDecodeFn_' + id + '("') + str + '");';
    src += 'document.getElementById("_urlDecodeFn_' + id + '").parentNode.removeChild(document.getElementById("_urlDecodeFn_' + id + '"));';
    script.src = src;
    document.body.appendChild(script);
}
_decode('characters to be decoded', 'gb2312', callback) // test // promise encapsulation var decode = function decode(str) {
    var charset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'gbk';
    return new Promise(function (resolve, reject) {
        try {
            _decode(str, charset, function (data) {
                resolve(data);
            });
        } catch (e) {
            resolve('Character decoding error.', e.toString());
        }
    });
};

Reference link: https://zhuanlan.zhihu.com/p/35537480

This is the end of this article about the front-end implementation of GBK and GB2312 string encoding and decoding (summary). For more relevant string GBK and GB2312 encoding and decoding content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

<<:  Why does your height:100% not work?

>>:  How to load the camera in HTML

Recommend

CSS uses the autoflow attribute to achieve seat selection effect

1. Autoflow attribute, if the length and width of...

HTML iframe usage summary collection

Detailed Analysis of Iframe Usage <iframe frame...

JavaScript implements circular carousel

This article shares the specific code of JavaScri...

Keepalived implements Nginx load balancing and high availability sample code

Chapter 1: Introduction to keepalived The purpose...

5 VueUse libraries that can speed up development (summary)

Table of contents What utilities does VueUse have...

How to set mysql to case insensitive

mysql set to case insensitive Windows Go to the d...

Detailed explanation of keepAlive usage in Vue front-end development

Table of contents Preface keep-avlive hook functi...

Detailed explanation of Linux CPU load and CPU utilization

CPU Load and CPU Utilization Both of these can re...

MySQL Oracle and SQL Server paging query example analysis

Recently, I have done a simple study on the data ...

MySQL5.7.21 decompressed version installation detailed tutorial diagram

Since I often install the system, I have to reins...

Commonplace talk about MySQL event scheduler (must read)

Overview MySQL also has its own event scheduler, ...

Navicat for MySQL 11 Registration Code\Activation Code Summary

Recommended reading: Navicat12.1 series cracking ...