idle-detector-x
v1.0.0
Published
一个轻量级的用户空闲状态检测库,支持跨标签页同步。
Readme
idle-detector-x
一个轻量级的用户空闲状态检测库,支持跨标签页同步。
安装
npm install idle-detector-x功能特性
- 🔍 自动检测用户空闲状态
- 🔄 支持跨标签页同步(基于 localStorage)
- ⚙️ 可配置超时时间
- 📦 支持 CommonJS 和 ES Module 两种模块格式
- 🪶 轻量级,无依赖
使用方法
基础用法
import IdleDetector from 'idle-detector-x'
const detector = new IdleDetector({
timeout: 30 * 60 * 1000, // 空闲超时时间,默认 30 分钟
crossTab: true, // 是否跨标签页同步,默认 true
onIdle: () => {
console.log('用户已空闲')
},
onActive: () => {
console.log('用户已激活')
}
})
detector.start() // 开始检测
detector.stop() // 停止检测配置选项
| 参数 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| timeout | number | 1800000 (30分钟) | 空闲超时时间(毫秒) |
| crossTab | boolean | true | 是否启用跨标签页同步 |
| onIdle | function | () => {} | 用户进入空闲状态的回调函数 |
| onActive | function | () => {} | 用户从空闲状态恢复活跃的回调函数 |
API
start()
开始检测用户空闲状态。
stop()
停止检测并清除定时器。
reset()
重置空闲计时器,通常在用户活动时自动调用。
监听的用户活动事件
库会自动监听以下用户活动事件:
mousemove- 鼠标移动mousedown- 鼠标按下keydown- 键盘按下scroll- 页面滚动touchstart- 触摸开始
跨标签页同步
当 crossTab 选项启用时,库会使用 localStorage 在同一域名的不同标签页之间同步用户活动状态。当任意一个标签页检测到用户活动时,其他标签页也会重置空闲计时器。
构建产物
项目构建后会生成以下文件:
dist/index.cjs.js- CommonJS 格式dist/index.esm.js- ES Module 格式
许可证
MIT
