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>
相关推荐
ghost1436 分钟前
C#学习第18天:特性(Attributes)
开发语言·学习·c#
会讲英语的码农13 分钟前
php基础
开发语言·后端·php
ptu小鹏4 小时前
类和对象(中)
开发语言·c++
来自星星的坤5 小时前
Vue 3中如何封装API请求:提升开发效率的最佳实践
前端·javascript·vue.js
vvilkim6 小时前
全面解析React内存泄漏:原因、解决方案与最佳实践
前端·javascript·react.js
vvilkim6 小时前
React批处理(Batching)更新机制深度解析
前端·javascript·react.js
Bayi·6 小时前
前端面试场景题
开发语言·前端·javascript
碎梦归途6 小时前
23种设计模式-结构型模式之享元模式(Java版本)
java·开发语言·jvm·设计模式·享元模式
Xiaoyu Wang6 小时前
Go协程的调用与原理
开发语言·后端·golang
bigear_码农7 小时前
python异步协程async调用过程图解
开发语言·python·线程·进程·协程