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

Detailed explanation of rpm installation in mysql

View installation and uninstallation # View rpm -...

Douban website's method for making small changes to website content

<br />Reading is a very important part of th...

How to solve the problem that MySQL cannot start because it cannot create PID

Problem Description The MySQL startup error messa...

Implementing WeChat tap animation effect based on CSS3 animation attribute

Seeing the recent popular WeChat tap function, I ...

Basic JSON Operation Guide in MySQL 5.7

Preface Because of project needs, the storage fie...

How to use translate and transition in CSS3

I always feel that translate and transition are v...

How to deeply understand React's ref attribute

Table of contents Overview 1. Creation of Refs ob...

Vue integrates Tencent TIM instant messaging

This article mainly introduces how to integrate T...

How to install babel using npm in vscode

Preface The previous article introduced the insta...

Two types of tab applications in web design

Nowadays, tabs are widely used in web design, but...

Vue+spring boot realizes the verification code function

This article example shares the specific code of ...

How to build YUM in Centos7 environment

1. Enter the configuration file of the yum source...