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>
相关推荐
dhxhsgrx1 小时前
PYTHON训练营DAY25
java·开发语言·python
GISer_Jing2 小时前
前端性能指标及优化策略——从加载、渲染和交互阶段分别解读详解并以Webpack+Vue项目为例进行解读
前端·javascript·vue
不知几秋2 小时前
数字取证-内存取证(volatility)
java·linux·前端
水银嘻嘻3 小时前
08 web 自动化之 PO 设计模式详解
前端·自动化
风逸hhh3 小时前
python打卡day25@浙大疏锦行
开发语言·python
刚入门的大一新生3 小时前
C++初阶-string类的模拟实现与改进
开发语言·c++
chxii5 小时前
5java集合框架
java·开发语言
老衲有点帅5 小时前
C#多线程Thread
开发语言·c#
C++ 老炮儿的技术栈5 小时前
什么是函数重载?为什么 C 不支持函数重载,而 C++能支持函数重载?
c语言·开发语言·c++·qt·算法