不同窗口传参

1.比较常用的就是window.open()

  1)第一个参数是url,

  2)第二个参数给新窗口的名字(name),并不是新窗口在窗口显示的title,在窗口下,通过window.name的方式拿到。这里也可以设置_self(在旧窗口打开新窗口),_blank(重新打开新窗口,默认就是该模式)

  3)第三个参数窗口宽高等

想同时设置name跟是否新开可以这样写

var targetWindow = window.open('http://localhost:8081/', '_self')
 targetWindow.name = 'demo'

2.使用postMessage的方式(使用环境:Vue)

  • 第一个参数,就是传递的消息message,可以使用字符串,信息过多可以使用JSON.stringify()的方式
  • 第二个参数,就是发送的url地址,也可以使用*来代替,但是不安全

介绍方

 window.addEventListener("message",(e) => {
     // 判断是否是旧窗口发过来的,这个if判断是必须的,然后会多接收一些不想接收的消息,就是信息还没有发送过来,绑定message事件会有默认信息
     if (e.origin !== "http://localhost:8080") return;
     // e.data——接收到的信息
     // e.origin——发送发的url地址,如果没有if判断,就会返回接收方的url(默认信息)
     // e.source——发送方的window引用,如果没有if判断,就会返回接收方的window(默认信息)
     // e.origin和e.source结合可以让接收方向发送方发送信息,从而达到双向通信
     console.log(e.data)
  })

发送方

 <template>
   <div id="app">
     <button @click="open">打开新窗口</button>
   </div>
 </template>
 ​
 export default {
   name: 'App',
   data () {
     this.targetWindow = null
     return {
     }
   },
   methods: {
     open() {
       this.targetWindow = window.open('http://localhost:8081/', '_blank', 'left=100,top=100,width=400,height=400')
       // 为什么加定时器,主要是为了防止window.open()异步加载,页面没有加载出来,就把消息发送出去了,有更好的方式也可以使用其他方式
       setTimeout(() => {
         this.targetWindow.postMessage('旧窗口向新窗口发送的消息', 'http://localhost:8081/')
       }, 1000)
     }
   }
 }
 </script>

参考链接https://juejin.cn/post/7264475859658342456

posted @ 2023-11-08 15:49  何歡  阅读(33)  评论(0)    收藏  举报