王一之 发表于 2023-3-17 15:24:07

【内测】高级统计库

## 脚本高级统计
> 这是一个内测中的功能

这是一个类似网站统计工具的库,引入后可以统计你脚本用户的使用情况,例如:脚本版本分布、运行设备分析、用户数等等

演示脚本: [高级统计测试](https://scriptcat.org/script-show-page/882)

### 使用方式

该库需要你在脚本中引入,并执行代码,key可以从脚本统计/高级统计中获取,另外必须设置白名单,非白名单内数据不会收集,库引入方式推荐为指定版本号,否则脚本管理器无法更新库的缓存。

#### 推荐方式

```js
// @require https://scriptcat.org/lib/881/1.1.0/script-statistics.js
// @grant GM_setValue
// @grant GM_getValue
// @antifeature tracking

try {
    new SC_Statistic({
      key: "高级统计key",
    });
} catch (e) {
    console.warn("statistic failed: ", e);
}
```

#### 最简洁的方式

```js
// @require https://scriptcat.org/lib/881/1.1.0/script-statistics.js
// @antifeature tracking

try {
    new SC_Statistic({
      key: "高级统计key",
    });
} catch (e) {
    console.warn("statistic failed: ", e);
}
```

---

如果不设置请求方式参数,会默认按照xhr、GM_xhr的方式进行请求,可能有以下几种情况:

#### 使用ajax的方式收集数据(优先)
这种方式在某些网站下运行可能会因为CSP策略无法提交数据,但是无需声明GM权限

#### 使用GM_xhr的方式收集数据
当ajax方式错误时,会使用此方式,此方式需要声明GM权限,但是可以无视网站的CSP策略,如果都不支持数据将无法收集

```js
// @connect scriptcat.org
// @require https://test.scriptcat.org/lib/881/1.1.0/script-statistics.js
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_xmlhttpRequest
// @antifeature tracking
```

### 用户识别方式

#### GM方式(推荐)
在脚本头信息中声明GM_get/setValue权限,能够获取更加准确的用户识别
```js
// @grant GM_setValue
// @grant GM_getValue
```

#### 网站localStorage方式
无需声明GM权限,但是也无法准确识别用户,每一个域将会产生一个用户

#### 自定义
可以自定义使用以下方式,由脚本来确定唯一用户
```js
try {
    new SC_Statistic({
      key: "高级统计key",
      customHash(){
            return "customHash";
      }
    });
} catch (e) {
    console.warn("statistic failed: ", e);
}
```

### 退出数据收集
退出时数据收集使用`navigator.sendBeacon`实现,效果欠佳,类似于ajax方式受CSP限制,并且无法准确收集,后续可能更新替换其它更好的方法

### 参数声明

```js
new SC_Statistic({
    key: "高级统计key",// 必须,统计key
    whitelist: ["scriptcat.org"],// 在白名单内的域名才会统计,为空将会自动拉取后端配置
    banFrame: false,// 不收集iframe中的数据
    enableGM: true,// 开启GM请求
    enableXML: true,// 开启ajax请求
    customHash: undefind,// 自定义哈希
});
```

Djx-Ybelove 发表于 2024-3-21 17:57:57

大佬有没有一种朴素的方法统计脚本使用次数

王一之 发表于 2024-3-21 20:13:38

Djx-Ybelove 发表于 2024-3-21 17:57
大佬有没有一种朴素的方法统计脚本使用次数

这不就是

要么就自己假设服务器,脚本启动时请求一次服务器来计数

Djx-Ybelove 发表于 2024-3-21 21:01:20

王一之 发表于 2024-3-21 20:13
这不就是

要么就自己假设服务器,脚本启动时请求一次服务器来计数

好滴,感谢

Djx-Ybelove 发表于 2024-3-22 07:06:21

这个能返回脚本使用次数吗?

王一之 发表于 2024-3-22 09:37:20

Djx-Ybelove 发表于 2024-3-22 07:06
这个能返回脚本使用次数吗?

可以统计
页: [1]
查看完整版本: 【内测】高级统计库