You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Electron窗口跨内容追踪用户活动的实现方案咨询

解决Electron窗口内跨内容类型的闲置追踪问题

直接从渲染进程的文档层面监听输入事件会被iframe、PDF这类独立内容容器阻断,换个思路——在主进程里监听Electron窗口本身的系统级输入事件,就能无视窗口内的内容类型,捕捉所有用户操作。

具体实现步骤:

  • 主进程绑定窗口输入事件
    给你的BrowserWindow实例绑定mouse-move、mouse-down、key-down、touch-start这些窗口级事件,只要用户在窗口范围内有操作(哪怕是在iframe或PDF里),这些事件都会触发。
    示例代码:

    const { app, BrowserWindow } = require('electron');
    const path = require('path');
    
    let mainWindow;
    let idleTimer;
    const IDLE_MINUTES = 5; // 闲置时间阈值,单位:分钟
    const IDLE_THRESHOLD = IDLE_MINUTES * 60 * 1000;
    
    function createWindow() {
      mainWindow = new BrowserWindow({
        width: 800,
        height: 600,
        webPreferences: {
          nodeIntegration: true,
          contextIsolation: false
        }
      });
    
      // 加载本地起始页
      mainWindow.loadFile(path.join(__dirname, 'start-page.html'));
    
      // 重置闲置计时器的逻辑
      const resetIdleTimer = () => {
        clearTimeout(idleTimer);
        idleTimer = setTimeout(() => {
          // 超时后切回本地起始页
          mainWindow.loadFile(path.join(__dirname, 'start-page.html'));
        }, IDLE_THRESHOLD);
      };
    
      // 监听所有窗口内的用户操作事件
      mainWindow.on('mouse-move', resetIdleTimer);
      mainWindow.on('mouse-down', resetIdleTimer);
      mainWindow.on('key-down', resetIdleTimer);
      mainWindow.on('touch-start', resetIdleTimer);
    
      // 窗口激活时重置计时器(避免窗口失活时误触发)
      mainWindow.on('focus', resetIdleTimer);
    
      // 窗口关闭时清理计时器
      mainWindow.on('closed', () => {
        clearTimeout(idleTimer);
        mainWindow = null;
      });
    
      // 初始化计时器
      resetIdleTimer();
    }
    
    app.whenReady().then(createWindow);
    
    app.on('window-all-closed', () => {
      if (process.platform !== 'darwin') app.quit();
    });
    
    app.on('activate', () => {
      if (BrowserWindow.getAllWindows().length === 0) createWindow();
    });
    
  • 关键说明

    • 这些窗口级事件是Electron基于系统消息封装的,不受页面内iframe、PDF等内容的限制,只要操作发生在窗口区域内就能被捕获。
    • 可根据需求补充监听mouse-up、key-up等事件,覆盖更多交互场景。
    • 若需要窗口最小化时暂停计时,可监听blur事件清除计时器,focus事件重新启动计时。

内容的提问来源于stack exchange,提问作者Torf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 10:55:16