最近有个需求需要网页调用插件,实现获取淘宝数据
大概思路如下:
export function cjPost(obj) {
return new Promise((resolve, reject) => {
let { funName, postData, timeout, isLoading = true } = { ...obj };
let timer = '';
obj['type'] = 'vue-send';//发送
obj['sign'] = getSign();//签名
let fun = (e) => {
if(e.data.sign && e.data.sign == obj.sign && e.data.type && e.data.type == 'plugin-send' ) {
setLoad(isLoading);
let res = e.data.data
// 滑块验证
if(isHk(res)) {
openHk(res.data.url);
}else{
resolve(res);
}
removeEventListener('message',fun);
clearTimeout(timer);
}
}
openLoading(isLoading);
postMessage(obj);
addEventListener('message',fun)
//超时销毁监听
timer = setTimeout(() => {
removeEventListener('message',fun);
reject({
state: false,
msg: '请求超时'
});
}, timeout || TIMEOUT);
})
}
$(function() {
// 监听网页发送
addEventListener('message', async function(e) {
if (e.data.type && e.data.type == 'vue-send') {
let funName = e.data.funName;
let postData = e.data.postData ? JSON.stringify(e.data.postData) : '';
if(!funName) {return}
let res = await eval(funName + '('+ postData +')');
let data = {
type: 'plugin-sed',
sign: e.data.sign,
data: res,
}
postMessage(data);
}
})
//淘宝h5接口调用函数
})