從零開始搭建前端監控系統(三)——實現控制iframe前進後退

前言

本系列文章旨在講解如何從零開始搭建前端監控系統。

項目已經開源

項目地址:

您的支持是我們不斷前進的動力。

喜歡請start!!!

喜歡請start!!!

喜歡請start!!!

本文是該系列第三篇,重點講解如何控制iframe的前進後退。

系列文章:

示例

https://abc-club.github.io/de...

演示

源碼

https://github.com/abc-club/demo

如果想看跟複雜的例子,可以看bombayjs的源碼

後臺截圖如下:

難點

document.getElementById('iframe id').contentWindow.history.back();

以上面這種方式控制會存在跨域問題!!!

原理

  1. 解決iframe的跨域問題,我們需要通過postMessage實現iframe的通信
  2. 通過window.history.back()和window.history.forward()控制前進後退

實現

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div>
    <iframe id='iframe'></iframe>
    <br/>
    url: <span id='url'></span>
    <br/>
    <button id='back' onclick='back()'>back</button>
    <button id='forward' onclick='forward()'>forward</button>
</div>
  <script>
    var url = './iframe.html'
    var div = document.getElementById('url'),
        iframe = document.getElementById('iframe')
    iframe.src = url
    div.innerHTML = url
    window.addEventListener('message', function(event) {
      if (!event.data.url) return
      div.innerHTML = event.data.url;
    }, false)


    function back() {
      iframe.contentWindow.postMessage('back', '*');
    }

    function forward() {
      iframe.contentWindow.postMessage('forward', '*');
    }

  </script>
</body>
</html>

iframe.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div>
    <a href='#a'>to #a</a>
    <p>1</p>
    <p>1</p>
    <p>1</p>
    <p>1</p>
    <p>1</p>
    <p>1</p>
    <p>1</p>
    <p>1</p>
    <p>1</p>
    <p>1</p>
    <p>1</p>
    <p id='a'>a</p>
    <p>2</p>
    <p>2</p>
    <p>2</p>
    <p>2</p>
    <p>2</p>
    <p>2</p>
    <p>2</p>
    <p>2</p>
</div>
  <script>
    window.addEventListener('message', function(event) {
      if (event.data === 'back') {
        window.history.back()
      } else {
        window.history.forward()
      }
    }, false)


    window.addEventListener('hashchange', function(event) {
      window.parent.postMessage({
        url: location.href
      }, '*')
      return
    }, false)
    
  </script>
</body>
</html>

更多資源

https://github.com/abc-club/f...

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章