Preface
A tricky problem I encountered when developing a project was that the product requires the search terms in the browser address bar to be retrieved from the browser for judgment. We generally use the UTF-8 encoding format, but Baidu and Google When encoding search terms, GBK encoding is used. This As a result, the decoding failed, so I looked for a solution on the Internet, and finally found a method compiled by a senior, and solved the problem through iframe, so I would like to summarize it for my own convenience in the future, and I hope it can help more people. People, I will put a link to the front-end article at the end.
1. Encoding (supports GBK and GB2312)
In order to avoid trouble, we can set the request page of the form to 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 closed. window:
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 child window directly window.close(); } function GBKEncode(str, charset, callback) { //Create form and encode through 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 submitted target document.body.appendChild(form); //Hide iframe intercepted 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, which requires the user to modify form.action = window.location.href; form.submit(); setTimeout(function () { form.parentNode.removeChild(form); iframe.parentNode.removeChild(iframe); }, 1000) //Remove node after 0.5 seconds} GBKEncode('Characters that need 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 (supports 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('Character 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 concludes this article about front-end implementation of string GBK and GB2312 encoding and decoding (summary). For more related string GBK and GB2312 encoding and decoding content, please search previous articles on downcodes.com or continue browsing below. Related articles, I hope you will support downcodes.com more in the future!