需求
A 页面中点击按钮可以打开新的标签页 B 并且向 B 页面发送消息数据。
当新的标签页 B 未关闭且符合同源策略时,再次点击按钮,可以自动跳转到标签页 B 并且发生消息数据。
B.html
<script>
  window.onmessage = evt => {
    console.log(evt.data);
  }
</script> 
页面自动定位方法
一、window.open(url, target)
A.html
<button>B Page</button>
<script>
  const button = document.querySelector("button");
  let child = null;
  button.addEventListener("click", () => {
    child = window.open("http://127.0.0.1:5500/B.html", "BPage");
    child.postMessage("hello");
  });
</script> 
Window:open() 方法 - Web API 接口参考 | MDN
参数 target: 一个不含空格的字符串,用于指定加载资源的浏览上下文的名称。如果该名称无法识别现有的上下文,则会创建一个新的上下文,并赋予指定的名称。还可以使用特殊的 target 关键字:_self、_blank、_parent 和 _top。
二、window.focus()
A.html
<button>B Page</button>
<script>
  const button = document.querySelector("button");
  let child = null;
  button.addEventListener("click", () => {
    if (child) {
      child.focus();
    } else {
      child = window.open("http://127.0.0.1:5500/B.html");
    }
    child.postMessage("hello");
  });
</script> 
三、a 超链接
<a href="http://127.0.0.1:5500/B.html" target="BPage">
  Open B Page
</a> 
运行
- 如上创建 A、B html 文件
 - 安装并使用 VsCode LiveServer 插件

 - 点击右下角状态栏的 “Go Live”

点击后(默认端口 5500):
 - 打开 http://127.0.0.1:5500/A.html 进行测试即可
 



















