js window.open 頁面之間的通訊(不同源)


一:a頁面
1:打開b頁面
let isB= window.open('b.html','b');

2:a頁面發送消息給b頁面
    isB.postMessage("dsddfsdf", 'b.html');
 
 
  二: b頁面
 
       b頁面接受a頁面的消息
 
 
window.onload = function() {
window.addEventListener('message', function(event) {
 //可以通過event.origin  判斷消息來源
 
console.log(event.data,'a發送來的消息');
//作為接受到消息的回應 同樣給a頁面發送一個消息
   
 
//如果a頁面沒有關閉
 if(window.opener){
     window.opener.postMessage('我是b,我收到消息了','a.html');
}else{
console.log("a頁面關閉了啊");
}
 
});
}
 
 
LAST:
 
在a頁面同樣添加 接受消息的事件  接受b接受消息的反饋信息
window.onload = function() {
window.addEventListener('message', function(event) {
//其他操作
})
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM