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>
相关推荐
bst@微胖子25 分钟前
Python高级语法之selenium
开发语言·python·selenium
王小义笔记30 分钟前
Postman如何流畅使用DeepSeek
开发语言·测试工具·lua·postman·deepseek
Smile_Gently2 小时前
前端:最简单封装nmp插件(组件)过程。
前端·javascript·vue.js·elementui·vue
java1234_小锋3 小时前
一周学会Flask3 Python Web开发-request请求对象与url传参
开发语言·python·flask·flask3
流星白龙5 小时前
【C++】36.C++IO流
开发语言·c++
诚信爱国敬业友善6 小时前
常见排序方法的总结归类
开发语言·python·算法
nihui1236 小时前
Uniapp 实现顶部标签页切换功能?
javascript·vue.js·uni-app
nbsaas-boot7 小时前
Go 自动升级依赖版本
开发语言·后端·golang
架构默片7 小时前
【JAVA工程师从0开始学AI】,第五步:Python类的“七十二变“——当Java的铠甲遇见Python的液态金属
java·开发语言·python
不只会拍照的程序猿8 小时前
从插入排序到希尔排序
java·开发语言·数据结构·算法·排序算法