Skip to content

编写 CNZZ 工具函数 #3

@Dream4ever

Description

@Dream4ever

需求描述

自己之前只是以最原始的方式给各个网站的前端页面添加了 CNZZ 统计代码,还有很多可以改进的地方,初步罗列如下:

  • 在页面中隐藏 CNZZ 生成的 HTML 元素
  • 加载完统计代码之后,再通过 JS 往页面中添加内部样式(和上面是同一个需求?)
  • 根据当前域名,加载对应的统计代码
  • 编写成 NPM 包,一次编写,到处使用

关于上面列出的第一项,CNZZ 统计代码用的是下面这种形式,最终会生成文字链接。但是由于 Chrome 的安全设置,会在浏览器控制台中出现第二段的提示代码,也就是说只有统计功能,但并不会显示文字连接。为了安全起见,还是需要在 CSS 中设置好样式,隐藏 CNZZ 统计内容。

<script src="https://s11.cnzz.com/z_stat.php?id=1260367303&web_id=1260367303" language="JavaScript"></script>` 
Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

方案调研

Google Analytics 与国内各家统计服务的对比

CNZZ 统计原理

自己编写 JS 插件 / NPM 包

现成的库/组件

应用过程

参考了 import和export用法总结raychenfj/vue-uweb,把函数写在 addcnzz.js 中:

const AddCnzz = () => {
  const hostName = window.location.hostname;
  const sites = [
    {
      domain: 'abc',
      id: '1234567890',
    },
    {
      domain: 'def',
      id: '9876543210',
    },
  ];
  const site = sites.find(ele => hostName.match(ele.domain)) || null;
  if (site) {
    const script = document.createElement('script');
    script.src = `https://s11.cnzz.com/z_stat.php?id=${site.id}&web_id=${site.id}`;
    document.body.appendChild(script);
  }
}

export default AddCnzz;

然后在 vue-cli 中用 import 指令引用它,最后在需要的地方,调用 AddCnzz() 函数就可以了。

要点总结

写一个自己的工具函数其实很简单嘛!

Metadata

Metadata

Assignees

No one assigned

    Labels

    Front-endEverything you see and experienceJSJavascriptStatisticsEverything about data

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions