1. 程式人生 > >父、子頁面同域、跨域時互相操作dom元素

父、子頁面同域、跨域時互相操作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...相關部分程式碼):

<!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>
<!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>

效果截圖: