How can an iframe child page pass a value to the parent page?

To pass values from an iframe child page to the parent page, you can use the properties and methods of the parent page’s window object.

  1. In a child page, one can access the parent page’s window object using window.parent.
  2. You can pass values to the parent page using the window.parent.postMessage() method, which allows you to send a message to the parent page and pass a data parameter.

In the subpage, you can pass values to the parent page using the following code:

// 子页面
var value = "这是要传递的值";
window.parent.postMessage(value, "*");

In the parent page, you can use window.addEventListener() to listen for messages from the child page and retrieve the passed values.

// 父页面
window.addEventListener('message', function(event) {
  // event.data就是传递的值
  console.log("接收到子页面传递的值:" + event.data);
});

It should be noted that the second parameter of the window.postMessage() method is the target window’s origin. You can typically use the wildcard “*” to allow messages from any source. If you only want to receive messages from specific sources, you can set this parameter to the corresponding origin.

Additionally, make sure that the child page and the parent page are within the same domain, otherwise cross-domain access will be restricted.

bannerAds