iframe父子页面之间可以通过以下几种方式进行数据传递:
父传子
1.URL参数传递
可以在iframe的src属性中通过URL参数的形式将数据传递给子页面,子页面可以通过location.search获取URL参数。
父页面:
<iframe src="child.html?name=John&age=25"></iframe>
子页面:
var params = new URLSearchParams(location.search);
var name = params.get('name');
var age = params.get('age');
console.log(name);
console.log(age);
2.postMessage方法传递
可以在父页面中通过postMessage方法向子页面发送消息,子页面中通过监听message事件获取消息。
父页面:
var iframe = document.querySelector('iframe');
$("button").click(function(){
iframe.contentWindow.postMessage('Hello', 'http://127.0.0.1:5501/iframe研究子页面.html');
})
子页面:
window.addEventListener('message', function(event) {
console.log(event.data); // 'Hello'
console.log(event.origin); // 'http://example.com'
});
注意:
(1)iframe.contentWindow.postMessage需要在事件中触发,直接传递无效
(2)postMessage方法的第二个参数必须是包含协议、主机名和端口的完整URL地址,否则会出现“Invalid target origin”错误。如果子页面和父页面不在同一个域名下,则需要使用正确的协议、主机名和端口来指定URL。
3.localStorage传递
可以在父页面中通过localStorage设置数据,子页面中通过监听storage事件获取数据。
父页面:
localStorage.setItem('name', 'John');
子页面:
window.addEventListener('storage', function(event) {
console.log(event.key); // 'name'
console.log(event.newValue); // 'John'
});
注意:localStorage只能监听同一域名下的数据变化,不同域名下的数据变化无法监听。
4.window对象传递
可以在父页面中通过window对象设置数据,子页面中通过window对象获取数据。
父页面:
window.myData = {
name: 'John', age: 25};
子页面:
console.log(window.myData); // {name: 'John', age: 25}
注意:这种方式的数据是共享的,任何页面都可以访问和修改这个数据,不够安全。
子传父
子页面可以通过parent获取到父页面的DOM,然后通过调用函数的形式传递数据
子页面:
parent.myfunction("张三") //parent.函数名(参数)
父页面:
myfunction(data){
console.log(data) //张三
}