gitpage Hugo统计每一篇文章浏览量

接上篇《博客迁移至hugo gitpage》后,因为缺失了每一篇文章的浏览量,而hugo又不具备这样的功能,原因还是gitpage不具备数据存储能力,自然就没办法统计每一篇文章的浏览量了。原本想使用自己服务器提供一个接口来记录,但发现https协议不支持调用http协议的接口,会出现block:mixed-content错误。

错误:https页面去发送http请求报错(浏览器阻止https发送http请求)

问题是明确了,但是我也没办法提供https的接口,免费的证书也用在了www.yuedun.wang上了。

后来想到了leancloud,直接在前端调用api,将数据存储在云端。

<script src="//cdn.jsdelivr.net/npm/leancloud-storage@4.11.1/dist/av-min.js"></script>
<script>
  // https://leancloud.cn/docs/sdk_setup-js.html#hash14962003 
  // https://leancloud.cn/docs/leanstorage_guide-js.html#hash813593086
  const appId = "xxx";
  const appKey = "xxx";
  const serverURL = "xxx";
  AV.init({ appId, appKey, serverURL });
  function updateCollect() {
    const collect = new AV.Query('Collect');
    const url = location.pathname;
    collect.select(['url', 'pv'])
    collect.equalTo('url', url);
    collect.first().then((col) => {
      if (!col) {
        // 声明 class
        const Collect = AV.Object.extend('Collect');
        // 构建对象
        const collect = new Collect();
        // 为属性赋值
        collect.set('url', url);
        collect.set('pv', 1);
        collect.save()
      } else {
        col.increment('pv', 1)
        col.save();

        // 元素不存在的情况
        try {
          const context = document.querySelector('.post__meta.meta');
          const pv = document.createElement('div');
          pv.setAttribute('class', 'meta__item-author meta__item');
          const span = document.createElement('span');
          span.setAttribute('class', 'meta__text');
          span.innerText = "浏览(" + col.get('pv') + ")";
          pv.appendChild(span)
          context.appendChild(pv)
        } catch (error) {
          console.error(error);
        }
      }
    });
  }

  updateCollect()
</script>

因为hugo-dpsg主题没有浏览量字段,所以通过js在对应的位置插入浏览量字段即可。

一直觉得leancloud这种在前端配置账号的方式不安全,但是也无所谓了,不是什么核心应用,数据也不重要,就这么使用也无妨。

当然,为了更进一步的安全,可以绑定域名。

在域名服务商那里设置一个三级域名,CNAME指向leancloud提供的CDN域名。绑定时间可能有点长,大概需要一天。