if (parent.__encode__iframe__callback__) { // 判断当前页面是否为子窗口
parent.__encode__iframe__callback__(location.search.split('=')[1]);
//直接关闭当前子窗口
window.close();
}
function GBKEncode(str, charset, callback) {
//创建form通过accept-charset做encode
var form = document.createElement('form');
form.method = 'get';
form.style.display = 'none';
form.acceptCharset = charset;
if (document.all) {
//如果是IE那么就调用document.charset方法
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__'; // 指定提交的目标的iframe
document.body.appendChild(form);
//隐藏iframe截获提交的字符串
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'; // 设置为空白
document.body.appendChild(iframe);
}
//
window.__encode__iframe__callback__ = function (str) {
callback(str);
if (document.all) {
document.charset = window.oldCharset;
}
}
//设置回调编码页面的地址,这里需要用户修改
form.action = window.location.href;
form.submit();
setTimeout(function () {
form.parentNode.removeChild(form);
iframe.parentNode.removeChild(iframe);
}, 1000) // 0.5秒后移除节点
}
GBKEncode('需要编码的字符', 'gb2312', callback);// 测试
// promise封装
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('字符编码错误.', e.toString());
}
});
};
|