父、子页面同域、跨域时互相操作dom元素

前端常见跨域解决方案

注意,同域或跨域下,父页面要操作子页面的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>

效果截图:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值