Преглед изворни кода

feat: 移除加密,支持自定义配置

zhangyuhan пре 2 година
родитељ
комит
5e0e2d4abe
7 измењених фајлова са 199 додато и 58 уклоњено
  1. 2 2
      package.json
  2. 40 22
      rollup.config.js
  3. 146 27
      src/easy-use-track.js
  4. 2 1
      src/index.js
  5. 1 1
      src/module/types.js
  6. 2 0
      src/module/utils.js
  7. 6 5
      src/plugins/click.js

+ 2 - 2
package.json

@@ -1,10 +1,10 @@
 {
   "name": "rollup-js",
-  "version": "1.1.7",
+  "version": "1.2.0",
   "main": "index.js",
   "license": "MIT",
   "scripts": {
-    "build": "rollup -c -w"
+    "build": "rollup -c"
   },
   "devDependencies": {
     "@babel/core": "^7.16.5",

+ 40 - 22
rollup.config.js

@@ -1,27 +1,45 @@
 import babel from 'rollup-plugin-babel';
-import { terser } from 'rollup-plugin-terser';
+import {terser} from 'rollup-plugin-terser';
 import resolve from 'rollup-plugin-node-resolve';
 import commonjs from 'rollup-plugin-commonjs';
+
 export default {
-    input: './src/index.js',
-    output: [
-        {
-            file: 'dist/j-track.min.js',
-            format: 'umd',
-            name: 'JTrack',
-            sourcemap: true,
-            global:{
-              'jquery': '$',
-              'CryptoJS': 'CryptoJS'
-            }
-        }
-    ],
-    plugins: [
-      resolve(),
-      commonjs(),
-      babel({
-          exclude: 'node_modules/**'
-      }),
-      terser()
-    ]
+  input: './src/index.js',
+  output: [
+    {
+      file: 'dist/j-track.min.js',
+      format: 'umd',
+      name: 'JTrack',
+      sourcemap: false,
+      globals: {
+        jquery: '$'
+      }
+    },
+    {
+      file: 'dist/j-track.amd.min.js',
+      format: 'amd',
+      name: 'JTrack',
+      sourcemap: false,
+      globals: {
+        jquery: '$'
+      }
+    },
+    {
+      file: 'dist/j-track.es.min.js',
+      format: 'es',
+      name: 'JTrack',
+      sourcemap: false,
+      globals: {
+        jquery: '$'
+      }
+    }
+  ],
+  plugins: [
+    resolve(),
+    commonjs(),
+    babel({
+      exclude: 'node_modules/**'
+    }),
+    terser()
+  ]
 }

+ 146 - 27
src/easy-use-track.js

@@ -1,5 +1,5 @@
 import Track from './core/index'
-import {getPlatform, loadJS} from './module/utils'
+import { getPlatform } from './module/utils'
 
 /**
  * 更简易地注入荟聚埋点统计
@@ -11,7 +11,9 @@ import {getPlatform, loadJS} from './module/utils'
 class EasyUse {
   constructor(options = {}) {
     const {
-      dataSourceBase = '//cdn-common.jianyu360.com/track/json/'
+      dataSourceBase = '//cdn-common.jianyu360.com/track/json/',
+      iframeSupportEnabled = true,
+      iframeSupportLink = '/test/huiju'
     } = options
 
     // 默认配置文件、版本号读取
@@ -24,12 +26,14 @@ class EasyUse {
     this.config = Object.assign({
       dataSource,
       version,
+      iframeSupportEnabled,
+      iframeSupportLink,
       upWaitStep: 200
     }, options)
     this.json = []
     this.params = {}
     this._running = false
-    this.init()
+    return this.init()
   }
 
   /**
@@ -37,7 +41,7 @@ class EasyUse {
    */
   init() {
     // 单例,禁止重复初始化事件绑定
-    if (this._running) return
+    if (this._running) return this
     this._running = true
     // 获取数据
     this.getDataJSON()
@@ -45,6 +49,7 @@ class EasyUse {
     this.addClickEventListener()
     this.addCustomClickEvent()
     this.addPageChangeListener()
+    return this
   }
 
   /**
@@ -52,20 +57,93 @@ class EasyUse {
    * @returns {boolean}
    */
   checkHasClabTracker () {
+    const pageTracker = this.checkHasPageClabTracker()
+    const iframeTracker = this.config.iframeSupportEnabled && typeof window._iframe_clab_tracker === 'function'
+    return pageTracker || iframeTracker
+  }
+
+  checkHasPageClabTracker () {
     return typeof window.clab_tracker !== 'undefined' && typeof window.clab_tracker?.track === 'function'
   }
 
+  /**
+   * 兼容 iframeSupport
+   * @returns {{}|*}
+   */
+  useClabTracker () {
+    if (this.checkHasClabTracker()) {
+      if (this.checkHasPageClabTracker()) {
+        return window.clab_tracker
+      } else {
+        return window._iframe_clab_tracker()
+      }
+    } else {
+      console.warn('[Helper Tracker]: not has clab_tracker')
+      return {}
+    }
+  }
+
+  /**
+   * 通过 iframeSupport 埋点
+   * @param callback
+   * @returns {*}
+   */
+  helperTracker (callback) {
+    // 检查 window.clab_xx 是否存在
+    if (typeof window._cl_tracker === 'object') {
+      // 如果存在,直接调用
+      return callback(window._cl_tracker)
+    }
+
+    var hId = 'helper-tracker-iframe'
+
+    function tryCallback (iframeNode) {
+      // 获取 iframe 的 window 对象
+      var iframeWindow = iframeNode.contentWindow;
+      // 检查 iframeWindow.clab_xx 是否存在
+      if (typeof iframeWindow._cl_tracker === 'object') {
+        // 调用 iframeWindow.clab_xx(data)
+        return callback(iframeWindow._cl_tracker)
+      } else {
+        console.warn('[Helper Tracker]: not find iframe clab')
+      }
+    }
+
+    // 检查是否已经存在 iframe
+    var existingIframe = document.getElementById(hId);
+
+    if (existingIframe) {
+      // 加载成功后的回调函数已经处理了调用逻辑
+      return tryCallback(existingIframe);
+    }
+
+    // 创建 iframe 元素
+    var iframe = document.createElement('iframe');
+    iframe.id = hId;
+    iframe.src = this.config.iframeSupportLink;
+    iframe.style.display = 'none';
+
+    // 加载成功后的回调函数
+    iframe.onload = function() {
+      tryCallback(iframe)
+    };
+
+    // 将 iframe 添加到文档中
+    document.body.appendChild(iframe);
+  }
+
+
   /**
    * 初始化JTrack SDK,通过荟聚SDK上报信息
    */
   addClickEventListener() {
     const _this = this
-    loadJS('https://cdn-common.jianyu360.com/cdn/lib/crypto/4.1.1/crypto-js.min.js', () => {
       const jyEventTrack = new Track()
       jyEventTrack.$subscribe.$on('CLICK-TRACK', function (transformedData, pageInfo) {
-        if (_this.checkHasClabTracker()) {
+        const tracker = _this.useClabTracker()
+        if (tracker && tracker.track) {
           try {
-            clab_tracker.track('c_jyclick', Object.assign({
+            tracker.track('c_jyclick', Object.assign({
               c_breakername: transformedData.data.content.substr(0, 15),
               c_pagename: pageInfo.href.title,
               c_platform: pageInfo.platform,
@@ -82,18 +160,40 @@ class EasyUse {
           }
         }
       })
-    })
+  }
+
+  /**
+   * 自定义上报埋点
+   * @param eventName
+   * @param data
+   */
+  addTrack (eventName, data = {}) {
+    const _this = this
+    const tracker = _this.useClabTracker()
+    if (tracker && tracker.track) {
+      try {
+        tracker.track(eventName, Object.assign({
+          date: new Date()
+        }, _this.getNowPageInfo('click'), data))
+      } catch (e) {
+        console.warn('!! Check Track JS Error 005 !!')
+      }
+    }
   }
 
   /**
    * 自定义埋点事件名称统计
    */
   addCustomClickEvent () {
+    const _this = this
     window.addEventListener('click', (e) => {
       try {
         const hasCustomEvent =  e.target.getAttribute('data-cl-event')
-        if (hasCustomEvent && this.checkHasClabTracker()) {
-          clab_tracker.track(hasCustomEvent)
+        if (hasCustomEvent) {
+          const tracker = _this.useClabTracker()
+          if (tracker && tracker.track) {
+            tracker.track(hasCustomEvent)
+          }
         }
       } catch (e) {
         console.warn('!! Check Track JS Error 002 !!')
@@ -105,7 +205,7 @@ class EasyUse {
    * 页面切换时上报访问事件
    */
   addPageChangeListener() {
-    window.addEventListener("popstate",  (e) => {
+    window.addEventListener("popstate",  () => {
       setTimeout(() => {
         this.upPageInfo()
       }, this.config.upWaitStep)
@@ -126,20 +226,26 @@ class EasyUse {
     }
 
     const params = this.getNowPageInfo('popstate')
-    try {
-      clab_tracker.ready(function () {
-        this.push({"pageType":"web"});
-        params.url = params.c_url
-        this.track("open_page", params);
-        clab_tracker.setEnableAutoTrackExitPage(false)
-      })
-    } catch (e) {
-      console.warn('!! Check Track JS Error 003 !!')
+    const tracker = this.useClabTracker()
+    if (tracker && tracker.ready) {
+      try {
+        tracker.ready(function () {
+          this.push({"pageType":"web"});
+          params.url = params.c_url
+          this.track("open_page", params);
+          tracker.setEnableAutoTrackExitPage(false)
+        })
+      } catch (e) {
+        console.warn('!! Check Track JS Error 003 !!')
+      }
     }
-    try {
-      clab_tracker.track('c_jy_open_page', params)
-    } catch (e) {
-      console.warn('!! Check Track JS Error 004 !!')
+
+    if (tracker && tracker.track) {
+      try {
+        tracker.track('c_jy_open_page', params)
+      } catch (e) {
+        console.warn('!! Check Track JS Error 004 !!')
+      }
     }
   }
 
@@ -208,9 +314,22 @@ class EasyUse {
     this.getJSON(`${this.config.dataSource}${this.config.version ? ('?v=' + this.config.version) : ''}`, (data) => {
       if (Array.isArray(data)) {
         this.json = [].concat(data)
-        setTimeout(() => {
-          this.upPageInfo()
-        }, this.config.upWaitStep)
+
+        if (!this.checkHasPageClabTracker() && this.config.iframeSupportEnabled) {
+          const _this = this
+          this.helperTracker(function (tracker) {
+            window._iframe_clab_tracker = function () {
+              return tracker
+            }
+            setTimeout(() => {
+              _this.upPageInfo()
+            }, _this.config.upWaitStep)
+          })
+        } else {
+          setTimeout(() => {
+            this.upPageInfo()
+          }, this.config.upWaitStep)
+        }
       }
     })
   }

+ 2 - 1
src/index.js

@@ -6,7 +6,8 @@ import EasyUse from './easy-use-track'
   if (!skipInit) {
     // 支持自定义配置
     const config = window._easy_track_config || {}
-    new EasyUse(Object.assign({}, config))
+    if (window.__EasyJTrack) { return }
+    window.__EasyJTrack = new EasyUse(Object.assign({}, config))
   }
 })();
 

+ 1 - 1
src/module/types.js

@@ -3,6 +3,6 @@ export const Subscribe = {
 }
 
 export const SDK_INFO = {
-  VERSION: '1.1.7',
+  VERSION: '1.2.0',
   PREFIX: 'JyTrack'
 }

+ 2 - 0
src/module/utils.js

@@ -29,6 +29,8 @@ export function getElementInfo(e, target) {
     event: e.type,
     element_id: eNode.getAttribute('id') || null,
     element_name: eNode.getAttribute('name') || null,
+    element_alt: eNode.getAttribute('alt') || null,
+    element_title: eNode.getAttribute('title') || null,
     element_text: getText(eNode),
     element_tag: eNode.nodeName,
     element_class: eNode.className,

+ 6 - 5
src/plugins/click.js

@@ -1,6 +1,5 @@
 import TrackPlugins from './base'
-import { getPlatform, getHref, getElementInfo, checkJqueryEventBind, checkVueEventBind, checkHasVue, checkHasJquery, throttle } from "../module/utils";
-import { getAES } from "../module/crypto"
+import { getElementInfo, checkJqueryEventBind, checkVueEventBind, checkHasJquery, throttle } from "../module/utils";
 
 export default class ClickPlugin extends TrackPlugins {
   constructor (_global) {
@@ -40,7 +39,8 @@ export default class ClickPlugin extends TrackPlugins {
         this.monitor()
       }
     }
-    this.pageInfo.id = getAES(this.pageInfo.href.pathname).toString()
+    // this.pageInfo.id = getAES(this.pageInfo.href.pathname).toString()
+    this.pageInfo.id = (this.pageInfo.href.pathname).toString()
     // _global.logger.log(`平台: ${this.pageInfo.platform} \n 标题: ${this.pageInfo.href.title} \n 页面路径: ${this.pageInfo.href.pathname} \n 唯一ID: ${this.pageInfo.id}`)
     // _global.logger.debug(`平台: ${this.pageInfo.platform} 标题: ${this.pageInfo.href.title} <br> 页面路径: ${this.pageInfo.href.pathname} <br>  唯一ID: ${this.pageInfo.id}`)
   }
@@ -54,11 +54,12 @@ export default class ClickPlugin extends TrackPlugins {
     const canClass = allowClass.filter(v => eInfo.element_class.indexOf(v) !== -1).length > 0
     if (collectedData.data.hasFn || allowTags.includes(eInfo.element_tag) || canClass) {
       const result = {
-        key: getAES(eInfo.selector).toString(),
+        // key: getAES(eInfo.selector).toString(),
+        key: (eInfo.selector).toString(),
         type: 'click',
         data: {
           selector: eInfo.selector,
-          content: eInfo.element_text,
+          content: eInfo.element_text || eInfo.element_name || eInfo.element_alt || eInfo.element_title || eInfo.element_id,
           event_time: new Date().getTime(),
           event_fn: collectedData.data.hasFn,
           event_vue_fn: collectedData.data.hasVueFn