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

如何在Firefox浏览器插件中创建TouchEvent或等效触摸事件?

Great question! I've run into this exact issue with Firefox desktop before—here's what's going on and how to fix it:

Firefox desktop disables the TouchEvent constructor by default (it leans into PointerEvent for unified input handling across touch, mouse, and pen), which is why you're hitting that ReferenceError. But there are a few solid workarounds depending on your plugin's needs:

Option 1: Enable Native TouchEvent Support in Firefox

If you don't mind guiding your users through a quick setting change, you can have them enable TouchEvent natively:

  1. Have them type about:config into the Firefox address bar and accept the warning.
  2. Search for dom.w3c_touch_events.enabled.
  3. Set its value to 1 (auto-detect touch support) or 2 (force-enable touch events even without a touch screen).

Once enabled, your existing Chrome-compatible new TouchEvent(...) code will work in Firefox too. That said, this isn't ideal for a plugin that needs to work out of the box—so let's move to better options.

Option 2: Inject Event-Creation Logic Into the Page Context (Best for Out-of-the-Box Compatibility)

The problem with your initial CustomEvent attempt is Firefox's context isolation between content scripts and the main page. When you create an event in your plugin's content script and dispatch it, the browser uses structured cloning to pass the event to the page—and any custom properties you add get stripped out.

The fix is to inject your event-creation code directly into the page's global context, where you can attach the touches, targetTouches, and changedTouches properties directly to the event object (no cloning involved). Here's how to do it:

Step 1: Inject the Event-Dispatching Function

In your plugin's content script, inject a script into the page that listens for messages from your content script and creates the simulated touch events:

// Content script code
const injectScript = `
  window.addEventListener('message', (e) => {
    if (e.data.type !== 'SIMULATE_TOUCH') return;
    
    const { targetSelector, eventType, touchesData } = e.data;
    const target = document.querySelector(targetSelector) || document.body;
    
    // Create a TouchList populated with Touch objects
    const touchList = new TouchList();
    touchesData.forEach((touchData, index) => {
      const touch = new Touch({
        identifier: touchData.id,
        target: target,
        clientX: touchData.clientX,
        clientY: touchData.clientY,
        screenX: touchData.screenX,
        screenY: touchData.screenY
      });
      touchList[index] = touch;
    });

    let event;
    // Use native TouchEvent if available, else a custom event with touch properties
    if (typeof TouchEvent !== 'undefined') {
      event = new TouchEvent(eventType, {
        touches: touchList,
        targetTouches: touchList,
        changedTouches: touchList,
        bubbles: true,
        cancelable: true
      });
    } else {
      event = new CustomEvent(\`simulated-\${eventType}\`, {
        bubbles: true,
        cancelable: true
      });
      // Attach touch properties directly to the event (works in page context)
      event.touches = touchList;
      event.targetTouches = touchList;
      event.changedTouches = touchList;
    }

    target.dispatchEvent(event);
  });
`;

// Inject the script into the page
const scriptEl = document.createElement('script');
scriptEl.textContent = injectScript;
document.head.appendChild(scriptEl);
scriptEl.remove(); // Clean up after injection

Step 2: Trigger the Event From Your Content Script

Send a message to the injected script to dispatch the touch event:

// Content script code
window.postMessage({
  type: 'SIMULATE_TOUCH',
  targetSelector: '#your-target-element', // Or leave blank for document.body
  eventType: 'touchstart', // Can be 'touchmove', 'touchend', etc.
  touchesData: [
    {
      id: 0,
      clientX: 100,
      clientY: 200,
      screenX: 100,
      screenY: 200
    }
  ]
}, '*');

When the page receives this event, it'll have full access to the touches, targetTouches, and changedTouches properties just like a native TouchEvent.

Option 3: Simulate Touch Behavior with PointerEvents

Firefox recommends using PointerEvent as a unified API for all input types. If the pages your plugin targets can be adapted to listen for PointerEvent instead of TouchEvent, you can dispatch PointerEvent directly from your content script:

// Content script code
const target = document.querySelector('#your-target-element');
const pointerDownEvent = new PointerEvent('pointerdown', {
  pointerType: 'touch',
  clientX: 100,
  clientY: 200,
  bubbles: true,
  cancelable: true
});
target.dispatchEvent(pointerDownEvent);

If the page only listens for TouchEvent, you can extend the injected script from Option 2 to convert PointerEvent into simulated TouchEvent for full compatibility.

Final Notes

  • The context isolation trick (Option 2) is the most reliable way to get your custom touch events working in Firefox without requiring user settings changes.
  • Firefox mobile does support the TouchEvent constructor by default, so your plugin will work there without extra code.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 06:35:31