You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从JS打开的新窗口向原有窗口执行JavaScript代码

该需求完全可以实现,你打开的子窗口与原窗口符合同源策略,可通过两种常用方案实现跨窗口调用:

方案一:直接通过 window.opener 调用父窗口方法

该方案写法简洁,适合当前同源场景使用:

// 父窗口预先暴露可被子窗口调用的方法
window.callFromChild = function(data) {
  console.log('子窗口触发父窗口代码,接收到的参数:', data);
  // 此处写原窗口需要执行的业务逻辑
}

const winHtml = `
<button id="cool">Run code on other window</button>
<script>
  document.querySelector('#cool').addEventListener('click', () => {
    // 调用前先判断父窗口是否存在、未关闭,避免报错
    if (window.opener && !window.opener.closed) {
      window.opener.callFromChild('来自子窗口的参数');
    }
  })
</script>
`;

const winUrl = URL.createObjectURL(
    new Blob([winHtml], { type: "text/html" })
);

const win = window.open(
    winUrl,
    "win",
    `width=800,height=400,screenX=200,screenY=200`
);

方案二:使用 postMessage 通信

该方案安全性更高,同时兼容跨域场景,生产环境更推荐使用:

// 父窗口监听子窗口发送的消息
window.addEventListener('message', (e) => {
  // 安全校验:确认消息来源是你打开的可信子窗口
  if (e.source === win) {
    console.log('收到子窗口消息,触发父窗口逻辑,消息内容:', e.data);
    // 此处写原窗口需要执行的业务逻辑
  }
})

const winHtml = `
<button id="cool">Run code on other window</button>
<script>
  document.querySelector('#cool').addEventListener('click', () => {
    if (window.opener && !window.opener.closed) {
      // 生产环境建议把第二个参数的通配符*替换为父窗口的实际源地址,避免安全风险
      window.opener.postMessage('需要传递的参数', '*');
    }
  })
</script>
`;

const winUrl = URL.createObjectURL(
    new Blob([winHtml], { type: "text/html" })
);

const win = window.open(
    winUrl,
    "win",
    `width=800,height=400,screenX=200,screenY=200`
);

内容的提问来源于stack exchange,提问作者ScriptSecure Services

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 18:54:02