머리말
프로젝트를 개발할 때 직면했던 다소 까다로운 문제는 제품이 판단을 위해 브라우저 주소 표시줄의 검색어를 브라우저에서 검색해야 한다는 것입니다. 우리는 일반적으로 UTF-8 인코딩 형식을 사용하지만 Baidu와 Google은 검색어를 인코딩할 때, GBK 인코딩이 사용됩니다. 결과적으로 디코딩이 실패해서 인터넷에서 해결 방법을 찾다가 결국 선배님이 정리한 방법을 찾아 iframe을 통해 문제를 해결했기 때문에 앞으로는 제 편의상 정리해서 정리하고자 합니다. 그리고 더 많은 분들에게 도움이 되었으면 좋겠습니다. 마지막에 프론트엔드 기사 링크를 걸어 놓겠습니다.
1. 인코딩(GBK 및 GB2312 지원)
문제를 피하기 위해 양식의 요청 페이지를 현재 페이지로 설정하고 JS 페이지 앞에 콜백 함수를 넣을 수 있습니다. 이런 식으로 이 페이지에 상위 페이지가 있고 __encode__iframe__callback__이 정의되면 콜백이 발생합니다. 직접 실행하고 창을 닫을 수 있습니다.
if (parent.__encode__iframe__callback__) { // 현재 페이지가 자식 창인지 확인 parent.__encode__iframe__callback__(location.search.split('=')[1]);
//현재 자식 창을 직접 닫습니다. window.close();
}
함수 GBKEncode(str, charset, 콜백) {
//양식을 생성하고 accept-charset을 통해 인코딩합니다.
var form = document.createElement('form');
form.method = '가져오기';
form.style.display = '없음';
form.acceptCharset = 문자셋;
if (document.all) {
//IE라면 document.charset 메소드를 호출합니다. window.oldCharset = document.charset;
document.charset = 문자셋;
}
var input = document.createElement('input');
input.type = '숨김';
input.name = 'str';
입력.값 = str;
form.appendChild(입력);
form.target = '__encode__iframe__' // 제출된 타겟의 iframe을 지정합니다.
document.body.appendChild(form);
//iframe이 차단한 제출 문자열 숨기기 if (!window['__encode__iframe__']) {
var iframe;
iframe = document.createElement('iframe');
iframe.setAttribute('name', '__encode__iframe__');
iframe.style.display = '없음';
iframe.width = "0";
iframe.height = "0";
iframe.scrolling = "아니요";
iframe.allowtransparency = "true";
iframe.frameborder = "0";
iframe.src = 'about:blank'; // 공백으로 설정 document.body.appendChild(iframe);
}
//
window.__encode__iframe__callback__ = 함수 (str) {
콜백(str);
if (document.all) {
document.charset = window.oldCharset;
}
}
//사용자가 수정해야 하는 콜백 인코딩 페이지의 주소를 설정합니다. form.action = window.location.href;
양식.제출();
setTimeout(함수 () {
form.parentNode.removeChild(form);
iframe.parentNode.removeChild(iframe);
}, 1000) //0.5초 후 노드 제거}
GBKEncode('인코딩해야 하는 문자', 'gb2312', callback);//Test//캡슐화 약속 var encode = function encode(str) {
var charset = 인수.길이 > 1 && 인수[1] !== 정의되지 않음 인수[1] : 'gbk';
return new Promise(함수 (해결, 거부) {
노력하다 {
_encode(str, charset, 함수(데이터) {
해결(데이터);
});
} 잡기 (e) {
해결('문자 인코딩 오류.', e.toString());
}
});
};2. 디코딩(GBK, GB2312, Base64 지원)
함수randomId() {
var 텍스트 = "";
var 가능 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++) {
텍스트 += available.charAt(Math.floor(Math.random() * available.length));
}텍스트를 반환합니다.
}
function _decode(str, charset, 콜백) {
var script = document.createElement('script');
var id = randomId(); // 충돌을 방지하기 위해 고유 ID를 생성합니다. script.id = '_urlDecodeFn_' + id;
window['_urlDecodeFn_' + id] = 콜백;
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(스크립트);
}
_decode('디코딩할 문자', 'gb2312', callback) // 테스트 // 캡슐화 약속 var decode = function decode(str) {
var charset = 인수.길이 > 1 && 인수[1] !== 정의되지 않음 인수[1] : 'gbk';
return new Promise(함수 (해결, 거부) {
노력하다 {
_decode(str, charset, 함수(데이터) {
해결(데이터);
});
} 잡기 (e) {
해결('문자 디코딩 오류.', e.toString());
}
});
};참조 링크: https://zhuanlan.zhihu.com/p/35537480
이것으로 문자열 GBK 및 GB2312 인코딩 및 디코딩의 프런트엔드 구현(요약)에 대한 기사를 마칩니다. 더 많은 관련 문자열 GBK 및 GB2312 인코딩 및 디코딩 콘텐츠를 보려면 downcodes.com에서 이전 기사를 검색하거나 아래에서 계속해서 관련 기사를 찾아보세요. 앞으로도 downcodes.com을 더 많이 지원해 주시기 바랍니다!