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>
相关推荐
袁煦丞几秒前
2025.8.18实验室【代码跑酷指南】Jupyter Notebook程序员的魔法本:cpolar内网穿透实验室第622个成功挑战
前端·程序员·远程工作
Fine姐2 分钟前
The Network Link Layer: 无线传感器中Delay Tolerant Networks – DTNs 延迟容忍网络
开发语言·网络·php·硬件架构
Joker Zxc5 分钟前
【前端基础】flex布局中使用`justify-content`后,最后一行的布局问题
前端·css
无奈何杨8 分钟前
风控系统事件分析中心,关联关系、排行、时间分布
前端·后端
Moment14 分钟前
nginx 如何配置防止慢速攻击 🤔🤔🤔
前端·后端·nginx
晓得迷路了19 分钟前
栗子前端技术周刊第 94 期 - React Native 0.81、jQuery 4.0.0 RC1、Bun v1.2.20...
前端·javascript·react.js
江城开朗的豌豆20 分钟前
React Native 实战心得
javascript
HAPPY酷20 分钟前
给纯小白的Python操作 PDF 笔记
开发语言·python·pdf
前端小巷子21 分钟前
Vue 自定义指令
前端·vue.js·面试
玲小珑27 分钟前
Next.js 教程系列(二十七)React Server Components (RSC) 与未来趋势
前端·next.js