JS子頁面調用父頁面的方法


方法1: 子頁面關閉后觸發父頁面的方法

// 父頁面
const winObj = window.open(url.href); const loop = setInterval(() => { if (!winObj) { return; } if (winObj.closed) { clearInterval(loop);
     // 父頁的自定義方法
this.refreshTable(); } }, 1);

// 子頁面
function xxx(){
  window.close();
}
  

方法2.子頁面調用父頁面的方法

// 父頁面
 window.open(url.href);
 window.addEventListener('message', (data: any) => {
    // 這個true是子頁面傳遞過來的是string.可以自定義其他
      if (data.data === 'true') {
     // 父頁面的自定義方法
        this.refreshTable();
      }
    }); 

// 子頁面
 function xxx(){
  // 給父頁面傳值 window.opener.postMessage(
'true'); }
// addEventListener 會導致重復觸發 可改用 onmessage 方法
// 父頁面

window.onmessage = (data: any) => {
      if (data.data === 'true') {
        this.refreshTable();
      }
    };
// 子頁面
window.opener.postMessage('true');
 

 


免責聲明!

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



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