【JS】浏览器不同窗口、标签页或 iframe之间的通讯 - 技术的尽头是魔术

效果

  • 左上↖地址: http://127.0.0.1:5500/index.html
  • 左下↙地址: http://127.0.0.1:5500/index.html?hidden
  • 右上↗地址: http://127.0.0.1:5500/index.html?hidden
  • 右下↘地址: http://127.0.0.1:5500/index.html?hidden
    【JS】浏览器不同窗口、标签页或 iframe之间的通讯 - 技术的尽头是魔术_第1张图片

index.html

DOCTYPE html>
<html>
  <head>
    <title>cardtitle>
    <link type="text/css" rel="styleSheet" href="index.css" />
  head>
  <body>
    <div id="card" class="card">
      <img src="A.png"/>
    div>
    <script src="index.js">script>
  body>
html>

index.css

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body{
  width: 100vw;
  height: 100vh;
  margin: 0;
  /* backgroud: #191c29 */
  background: #fff;
}
.card{
  width: 100px;
  height: 200px;
  /* 设置定位类型为相对定位 */
  position: relative;
}

img{
  width: 200px;
  height: 300px;
}

index.js

//获取card元素
const card = document.querySelector('.card');
const BAR = 79;
/**
 * @function 将"屏幕上的点"转换为"浏览器页面客户区域的点"
 * @param screenX number 
 * @param screenY number
 * @returns object
 * @returns object.clientX number
 * @returns object.clientY number
 */
function getClientPoint(screenX, screenY) {
  const clientX = screenX - window.screenX;
  const clientY = screenY - window.screenY-BAR;
  return [clientX, clientY];
}
/**
 * @function 将"浏览器页面客户区域的点"转换为"屏幕上的点"
 * @param screenX number 
 * @param screenY number
 * @returns object
 * @returns object.clientX number
 * @returns object.clientY number
 */
function getScreenPoint(clientX, clientY) {
  const screenX = clientX + window.screenX;
  const screenY = clientY + window.screenY + BAR;
  return [screenX, screenY];
}

//添加鼠标按下事件
card.onmousedown = (e) => {
  let x = e.pageX - card.offsetLeft;
  let y = e.pageY - card.offsetTop;
  //添加鼠标移动事件
  window.onmousemove = (e) => {
    const cx = e.pageX - x;
    const cy = e.pageY - y;
    card.style.left = cx + 'px';
    card.style.top = cy + 'px';
    //通知其他窗口
    console.log(e);
    console.log(channel);
   //使用 postMessage() 来发送消息给其他页面
   channel.postMessage(getScreenPoint(cx, cy));
  };
  //处理鼠标抬起事件
  window.onmouseup = (e) => {
    //移出鼠标移动处理事件
    window.onmousemove = null; 
    //移出鼠标抬起处理事件
    window.onmouseup = null;
  };
};

function init(){
  /*查询地址栏是否包含hidden参数*/
  if(location.search.includes('hidden')){
    /*将浏览器客户区包含hidden参数移出客户区*/
    card.style.left = '-1000px';
  }
}

init();

//BroadcastChannel 是 JavaScript 中的一个接口,用于在不同的浏览上下文之间进行通信。它允许在相同域名下的不同窗口、标签页或 iframe 之间发送消息。
const channel = new BroadcastChannel('card');

//onmessage 事件处理程序来接收其他页面发送的消息。
channel.onmessage = (e) => {
  const [cx,cy] = getClientPoint(...e.data);
  card.style.left = cx +'px';
  card.style.top = cy + 'px';
}

A.png

【JS】浏览器不同窗口、标签页或 iframe之间的通讯 - 技术的尽头是魔术_第2张图片

你可能感兴趣的:(语言-HTML,roadcastChannel,js,onmessage,postMessage,跨页面通讯,浏览器)