从零开始搭建前端监控系统(二)——实现圈选(无埋点)

3,876 阅读1分钟

前言

本系列文章旨在讲解如何从零开始搭建前端监控系统。

项目已经开源

项目地址:

您的支持是我们不断前进的动力。

喜欢请start!!!

喜欢请start!!!

喜欢请start!!!

本文是该系列第二篇,重点讲解如何实现圈选功能。

如果你还不了解怎么捕获click事件,请先看第一篇

系列文章:

示例

bombayjs.github.io/bombayjs/ex…

演示

源码

github.com/bombayjs/bo…

原理

  1. 通过postMessage实现iframe的通信
  2. 通过监听mouseover事件来圈选
  3. 通过监听click事件获取点击目标的路径
  4. 通过stopPropagation阻止原来的点击事件

实现

parent

<!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' src='./a.html'></iframe>
</div>
  <script>
    window.addEventListener('message', function(event) {
      console.log(event.data.path)
    }, false)

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

iframe

// a.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'>click me</a>
</div>
  <script>
    window.addEventListener('message', function(event) {
      console.log(event.data.path)
    }, false)


    window.addEventListener('click', function(event) {
      event.stopPropagation()
      window.parent.postMessage({
        path: '此处需要自己解析出元素路径'
      }, '*')
      return
    }, false)
    
    window.addEventListener('mouseover', function(event) {
      event.target.style = 'border: #ff0000 solid 1px'
    }, false)
  </script>
</body>
</html>

更多资源

github.com/abc-club/fr…