gxd-vue-library
Version:
依赖与element Ui插件库,聚福宝福利PC端插件库
93 lines (81 loc) • 2.29 kB
JavaScript
;
class PostMessages {
post;
fnc;
isParent;
options;
childrenStatus;
constructor(options ={}, isParent = true) {
this.options = options;
this.isParent = isParent;
if(isParent && !options['el']) throw new Error(`iframe ID is undefined,value:${options['el']}`);
if(window.postMessage) {
this.fnc = {};
this.listener();
if(this.isParent) this.checkIframe()
}
else throw new Error('window.postMessage is not support');
}
checkIframe(){
if(document.querySelector(this.options['el']) === null) {
setTimeout(()=>{
this.checkIframe();
}, 200)
}
else {
document.querySelector(this.options['el']).onload = ()=>{
this.childrenStatus = true;
}
}
}
handleListener(fnName,data){
if(this.fnc[fnName] && this.fnc[fnName].length > 0) {
this.fnc[fnName].map(fnc=>{
fnc(data)
})
}
else console.warn(`Not Bind Event ${fnName}`);
}
listener(){
window.addEventListener("message",(ev)=>{
let dataTemp;
try{
dataTemp = JSON.parse(ev.data)
}catch(e){
dataTemp = ev.data
}
const {fnName, data} = dataTemp;
console.log('listener',dataTemp,ev)
this.handleListener(fnName,data)
})
}
sendEvent(fnName,data, local=false){
let dataStr = JSON.stringify({fnName, data});
if(local) {
window.postMessage(dataStr, '*');
return
}
if(this.isParent) {
if(this.childrenStatus) document.querySelector(this.options['el']).contentWindow.postMessage(dataStr, '*')
else setTimeout(()=>{
this.sendEvent(fnName,data)
},200)
}
else window.parent.postMessage(dataStr, '*')
}
addEvent(fnName, handler) {
if(this.fnc[fnName] === undefined) this.fnc[fnName] = [];
this.fnc[fnName].push(handler);
}
unEvent(fnName, handler){
if(this.fnc[fnName] && this.fnc[fnName].length > 0) {
this.fnc[fnName] = this.fnc[fnName].filter(fnc=>{
let newStr = handler.toString().replace(/\s/g,'');
let oldStr = fnc.toString().replace(/\s/g,'');
return !(fnName === fnc || newStr===oldStr)
});
console.log(`this.fnc[${fnName}]`,this.fnc[fnName])
}
}
}
export default PostMessages;