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

如何用IoHook实现Puppeteer鼠标按下跟随拖拽功能?

Fixing Puppeteer Drag/Follow with Held Left Mouse Button

Hey there! The problem with your current code is that page.mouse.click() is a convenience method that presses and immediately releases the left mouse button—so it can't maintain a "held" state needed for dragging or drawing. Let's adjust this by mapping your local mouse's mousedown, mouseup, and mousemove events directly to Puppeteer's corresponding mouse methods.

Here's the revised code:

// Track if the local left mouse button is pressed
let isLeftButtonPressed = false;

// Handle local mouse button press
ioHook.on("mousedown", event => {
  // Check if it's the left button (IoHook uses 0 for left, 1 for middle, 2 for right)
  if (event.button === 0) {
    isLeftButtonPressed = true;
    const targetX = event.x;
    const targetY = event.y - 71; // Keep your existing offset adjustment
    
    // Press the left button in Puppeteer at the target position
    page.mouse.down({ button: 'left' });
    // Optional: Sync position immediately in case mousemove hasn't caught up
    page.mouse.move(targetX, targetY);
  }
});

// Handle local mouse button release
ioHook.on("mouseup", event => {
  if (event.button === 0) {
    isLeftButtonPressed = false;
    // Release the left button in Puppeteer
    page.mouse.up({ button: 'left' });
  }
});

// Handle local mouse movement (works for both regular move and drag)
ioHook.on("mousemove", event => {
  const targetX = event.x;
  const targetY = event.y - 71;
  
  // Move Puppeteer's mouse—if left button is pressed, this triggers dragging automatically
  page.mouse.move(targetX, targetY);
});

Key Changes Explained:

  • Track button state: We use isLeftButtonPressed to mirror your local mouse's left button state, so we only trigger Puppeteer's press/release when needed.
  • Use mouse.down() and mouse.up(): These methods let you control the button state explicitly—down holds the button, up releases it.
  • Drag behavior is automatic: When Puppeteer's mouse is moved while the left button is held down (via mouse.down()), it will behave exactly like a native drag operation.

Quick Notes:

  • Make sure your Puppeteer page is focused when running this code—unfocused pages might not register mouse events correctly.
  • If you ever run into a situation where Puppeteer's mouse gets stuck in a "pressed" state (e.g., your local mouse leaves the window), add a mouseleave event listener to trigger page.mouse.up() as a safety measure.
  • Double-check the event.button value if you're on a non-Windows system—IoHook's button codes are generally consistent, but it's worth verifying if you run into issues.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 09:13:35