编解码
JavaScript 内置编码函数
escape
> escape("王下邀月熊")
'%u738B%u4E0B%u9080%u6708%u718A'
其对应的解码函数为
> unescape('%u738B%u4E0B%u9080%u6708%u718A')
'王下邀月熊'
encodeURI
> encodeURI("http://王下邀月熊.com")
'http://%E7%8E%8B%E4%B8%8B%E9%82%80%E6%9C%88%E7%86%8A.com'
它对应的解码函数是
> decodeURI('http://%E7%8E%8B%E4%B8%8B%E9%82%80%E6%9C%88%E7%86%8A.com')
'http://王下邀月熊.com'
DOM 下GBK 编码
在
//创建form通过accept-charset做encode
const form = document.createElement("form");
form.method = "get";
form.style.display = "none";
form.acceptCharset = "gbk";
//创建伪造的输入
const input = document.createElement("input");
input.type = "hidden";
input.name = "str";
input.value = url;
//将输入框添加到表单中
form.appendChild(input);
form.target = "_urlEncode_iframe_";
document.body.appendChild(form);
//隐藏iframe截获提交的字符串
if (!window["_urlEncode_iframe_"]) {
const iframe = document.createElement("iframe");
//iframe.name = '_urlEncode_iframe_';
iframe.setAttribute("name", "_urlEncode_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._urlEncode_iframe_callback = callback;
//设置回调编码页面的地址,这里需要用户修改
form.action = window.location.href;
//提交表单
form.submit();
//定时删除两个子Element
setTimeout(function () {
form.parentNode.removeChild(form);
iframe.parentNode.removeChild(iframe);
}, 100);
即将
if (parent._urlEncode_iframe_callback) {
parent._urlEncode_iframe_callback(location.search.split("=")[1]);
//直接关闭当前子窗口
window.close();
}
在原文中还有关于
const urlencode = require("isomorphic-urlencode");
urlencode("王下邀月熊").then(function (data) {
console.log(data);
});
urlencode("王下邀月熊", "gbk").then(function (data) {
console.log(data);
});
在笔者自己以流式风格基于
//测试需要以GBK编码方式发起的请求
const urlencode = require("isomorphic-urlencode");
urlencode("左盼", "gbk").then((data) => {
fluentFetcher = new FluentFetcher({
host: "ggzy.njzwfw.gov.cn",
responseContentType: "text",
});
//http://ggzy.njzwfw.gov.cn/njggzy/consultant/showresault.aspx?ShowLsh=0&Mlsh=123456&Name=%D7%F3%C5%CE
//测试以代理模式发起请求
fluentFetcher
.parameter({ ShowLsh: "0", Mlsh: "123456", Name: data })
.get({ path: "/njggzy/consultant/showresault.aspx" })
.proxy({ proxyUrl: "http://app.truelore.cn:11499/proxy" })
.build()
.then((data) => {
console.log(data);
})
.catch((error) => {
console.log(error);
});
});