postmessage()在同一域名下,传递消息给另一个页面

这里是同域名下,getmessage.html(发送信息)传递消息给index.html(收到信息,并回传收到信息)

index.html页面

html 复制代码
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html charset=utf-8"/>
        
        <title>javascript变量声明的一些测试</title>
        <link rel="stylesheet" href="styles.css"/>
        
        
    </head>
    <body>
        <div id="firstdiv" style="width:900px;text-align: center;border:10px solid blue">
         <form id="form1" action="" method="post">  
         
         <input type="button" name="submit1" value="提交"/>
        </form> 
        <p id="msg"></p>
        </div>    
       
    </body>
    <script type="text/javascript" src="test.js"></script>
       
</html>

这里 是index.html页面中的test.js代码

javascript 复制代码
const btn=document.getElementsByName('submit1');

btn[0].addEventListener('click',()=>{
    let popup=window.open('getmessage.html');
    window.addEventListener('message',function(e){
        console.log(e);
        if(e.origin!='http://xuejs.xyz')return;
        //这里收到发来的信息,并显示
        document.getElementById('msg').innerHTML=e.data;
        e.source.postMessage('收到信息',e.origin);
    })
});

//这里是getmessage.html页面

javascript 复制代码
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html charset=utf-8"/>
        
        <title>接收postmessage传来的信息</title>
        
        <script type="text/javascript" src="eventutil.js"></script>
      
           
            
        </style>
    </head>
    <body>
        <p id="getmsg">waiting for message...</p>
       
    </body>
    
    <script type="text/javascript">

//window.opener表示打开getmessage.html页面的父页面
//这里用postMessage()传递了一条消息给index.html
        window.opener.postMessage('super window 接收到一条消息','/');
        //下面是接收index.html收到页面后的回传信息
       window.addEventListener('message',(e)=>{
        console.log(e);
        if(e.origin!='http://xuejs.xyz')return;
        console.log(e.data);
       });
    </script>
       
</html>
相关推荐
代钦塔拉15 小时前
第一篇:工业级 C++/Qt 项目头文件包含原则:告别循环依赖与编译玄学
开发语言·c++·qt
清灵xmf15 小时前
JS 原生深拷贝的终极方案——structuredClone
前端·javascript·vue.js·json.stringify·structuredclone
前端 贾公子15 小时前
响应式系统基础:依赖追踪的基础 —— 发布订阅模式(前端应用最广的设计模式)上
javascript·vue.js
谷雨不太卷15 小时前
Linux基础IO
java·开发语言
索西引擎15 小时前
【理论】TypeScript 函数重载:从 Vue 3 defineEmits 说起的类型安全实践
前端·typescript
女生也可以敲代码15 小时前
2026前端面试题精选:大厂高频考点与标准答案
前端
Jinuss15 小时前
代码质量管理工具-SonarQube
前端·代码规范
gCode Teacher 格码致知15 小时前
Javascript提高:使用canvas绘制一个绚丽的按钮-由Deepseek产生
javascript·css·css3
ZFSS16 小时前
WebExtrator 网页渲染与内容提取 API 使用指南
前端·人工智能·ai·ai编程
神仙别闹16 小时前
基于PHP+MySQL实现在线考试系统
开发语言·mysql·php