js iframe 如何通信,修改内容

1. js iframe 如何通信,修改内容

可以通过以下两种方式让 js iframe 之间进行通信:

  1. 使用 postMessage 方法

使用 postMessage 方法可以让 js 窗口之间进行跨域通信。方法如下:

在发送方窗口中(也就是 A 窗口):

const iframe = document.querySelector('#myIframe')
iframe.contentWindow.postMessage('hello', '*') // 向 B 窗口发送消息

在接收方窗口中(也就是 B 窗口):

window.addEventListener('message', event => {
  console.log(event.data) // 输出 'hello'
})

其中,第一个参数 event.data 表示接收到的消息,第二个参数指定接收消息的源窗口,* 表示接收所有来源窗口的消息。

  1. 使用 window.parent 和 window.frames

使用 window.parent 和 window.frames 可以让 js iframe 之间进行同源通信。方法如下:

在发送方 iframe 中:

window.parent.document.querySelector('#myIframe2').contentWindow.postMessage('hello', '*')

在接收方 iframe 中:

window.addEventListener('message', event => {
  console.log(event.data) // 输出 'hello'
})

其中,window.parent.documentwindow.frames 都指向父窗口,可以通过它们来访问其他同源 iframe 元素的方法和属性。

类似文章

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注