[Layui pop-up iframe data transfer between parent and child pages]

There are several ways to transfer data between iframe parent and child pages:


father to son

1. URL parameter passing

Data can be passed to subpages in the form of URL parameters in the src attribute of the iframe, and the subpages can obtain URL parameters through location.search.

Parent page:

<iframe src="child.html?name=John&age=25"></iframe>

Subpage:

var params = new URLSearchParams(location.search);
var name = params.get('name');
var age = params.get('age');
console.log(name);
console.log(age);

2. postMessage method delivery

You can send a message to the subpage through the postMessage method in the parent page, and obtain the message by listening to the message event in the subpage.

Parent page:

var iframe = document.querySelector('iframe');
$("button").click(function(){
    
    
   iframe.contentWindow.postMessage('Hello', 'http://127.0.0.1:5501/iframe研究子页面.html');
})

Subpage:

window.addEventListener('message', function(event) {
    
    
  console.log(event.data); // 'Hello'
  console.log(event.origin); // 'http://example.com'
});

Note:
(1) iframe.contentWindow.postMessage needs to be triggered in an event, and direct delivery is invalid
(2) The second parameter of the postMessage method must be a complete URL address including protocol, host name and port, otherwise "Invalid target origin" will appear mistake. If the child page is not under the same domain name as the parent page, you need to specify the URL with the correct protocol, hostname, and port.


3. LocalStorage delivery
You can set data through localStorage in the parent page, and obtain data by listening to storage events in the child page.

Parent page:

localStorage.setItem('name', 'John');

Subpage:

window.addEventListener('storage', function(event) {
    
    
  console.log(event.key); // 'name'
  console.log(event.newValue); // 'John'
});

Note: localStorage can only monitor data changes under the same domain name, and cannot monitor data changes under different domain names.


4. Window object transfer
Data can be set through the window object in the parent page, and data can be obtained through the window object in the child page.

Parent page:

window.myData = {
    
    name: 'John', age: 25};

Subpage:

console.log(window.myData); // {name: 'John', age: 25}

Note: The data in this method is shared, and any page can access and modify this data, which is not safe enough.


child's father

The child page can get the DOM of the parent page through the parent, and then pass the data by calling the function.
Child page:

parent.myfunction("张三")   //parent.函数名(参数)

Parent page:

myfunction(data){
    
    
	console.log(data)  //张三
}

Guess you like

Origin blog.csdn.net/qq_44749901/article/details/129872130