注意,同域或跨域下,父页面要操作子页面的dom元素,必须要等到子页面加载完毕,否则获取不了子页面的document,因此我们需要监听子页面的onload事件,或者监听父页面的onload事件也可以
注意,我们用window.frames['frameName'].window来获取子页面的window对象(为了兼容主流浏览器,需要设置iframe的id和name相同),或者用document.querySelector('#frameName').contentWindow来获取子页面的window对象,具体的兼容性如何请参考:各浏览器Iframe对contentWindow、contentDocument、document及frames属性测试
以下我用postMessage方法来做示例(同域时可直接粘贴运行以下示例,跨域时需要注释// 只有同域下才可以直接获取document并做操作,否则会报:Uncaught DOMException: Blocked a frame with origin...相关部分代码):
父页面http://localhost:3000/index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>demo</title>
<style>
* {
margin: 0;
padding: 0;
}
body,
html {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div>父</div>
<iframe id="myFrame" src="http://localhost:3000/test.html"></iframe>
</body>
<script>
var myFrame = document.querySelector('#myFrame')
// 子页面加载完毕后
myFrame.onload = function () {
// 子页面window对象
var childWindow = myFrame.contentWindow
childWindow.postMessage({ msg: '我是父页面的信息,要通知子页面改变字体大小', status: 200 }, '*')
// 只有同域下才可以直接获取document并做操作,否则会报:Uncaught DOMException: Blocked a frame with origin...
// 子页面document对象
var childDocument = childWindow.document
childDocument.querySelector('div').style.background = 'blue'
}
// 监听message事件
window.addEventListener('message', function (e) {
console.log('子页面说:', e.data)
if (e.data.status) {
document.querySelector('div').style.fontSize = '30px'
}
})
</script>
</html>
子页面http://localhost:3000/test.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>demo</title>
<style>
* {
padding: 0;
margin: 0;
}
body,
html {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<div>子</div>
</body>
<script>
// 父页面window对象
var parentWindow = window.parent
parentWindow.postMessage({ msg: '我是子页面的信息,要通知父页面改变字体大小', status: 200 }, '*')
// 只有同域下才可以直接获取document并做操作,否则会报:Uncaught DOMException: Blocked a frame with origin...
// 父页面document对象
var parentDocument = parentWindow.document
parentDocument.querySelector('div').style.background = 'red'
// 监听message事件
window.addEventListener('message', function (e) {
console.log('父页面说:', e.data)
if (e.data.status) {
document.querySelector('div').style.fontSize = '50px'
}
})
</script>
</html>
效果截图: