preventDefault、stopPropagation 和 cancelBubble 不足以阻止 contextMenu 尝试在 Firefox 移动测试视图中打开

preventDefault, stopPropagation, and cancelBubble not enough to prevent contextMenu from trying to open in Firefox mobile test view

如果你在 Firefox 桌面版本 91.0.2(当时最新)Windows10 64 位(可能还有其他版本)中打开 test URL 并打开 F12 菜单,然后单击响应式设计模式按钮(ctrl+shift+m​​...又名移动视图按钮)并按住左键单击图像左侧,您会看到数字上升到大约 25 - 然后停止并重置为零,并触发取消。我的理论是正常触发上下文菜单需要多长时间。

如果您在常规桌面视图或 Chrome 的常规桌面视图中尝试它 - 它按预期工作 - 它会计数到 100(甚至更多)直到你松手,然后 onFinish 被触发。

完整代码在这里:Code sandbox

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <meta name="theme-color" content="#000000" />
    <!--
      manifest.json provides metadata used when your web app is added to the
      homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
    <script>
      window.addEventListener(
        "contextmenu",
        function (e) {
          // do something here...
          e.preventDefault && e.preventDefault();
          e.stopPropagation && e.stopPropagation();
          e.cancelBubble = true;
          return false;
        },
        false
      );

      const noContext = document.getElementById("ItemImage");

      noContext.addEventListener("contextmenu", (e) => {
        e.preventDefault && e.preventDefault();
        e.stopPropagation && e.stopPropagation();
        e.cancelBubble = true;
        return false;
      });

      function absorbEvent_(event) {
        var e = event;
        e.preventDefault && e.preventDefault();
        e.stopPropagation && e.stopPropagation();
        e.cancelBubble = true;
        return false;
      }

      function preventLongPressMenu(node) {
        node.ontouchstart = absorbEvent_;
        node.ontouchmove = absorbEvent_;
        node.ontouchend = absorbEvent_;
        node.ontouchcancel = absorbEvent_;
      }

      function init() {
        preventLongPressMenu(document.getElementById("ItemImage"));
      }
    </script>
    <style>
      /* https://www.arungudelli.com/tutorial/css/disable-text-selection-in-html-using-user-select-css-property/ */
      .disable-select {
        user-select: none; /* supported by Chrome and Opera */
        -webkit-user-select: none; /* Safari */
        -khtml-user-select: none; /* Konqueror HTML */
        -moz-user-select: none; /* Firefox */
        -ms-user-select: none; /* Internet Explorer/Edge */
      }
    </style>
  </head>

  <body>
    <noscript>
      You need to enable JavaScript to run this app.
    </noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, you will see an empty page.

      You can add webfonts, meta tags, or analytics to this file.
      The build step will place the bundled scripts into the <body> tag.

      To begin the development, run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>

App.js

import React, { useCallback, useRef, useState } from "react";

import "./styles.css";
import { useLongPress } from "use-long-press";
import Item from "./Item";

function App() {
  const [progress, setProgress] = useState(0);
  const progressTimer = useRef();
  function handleTime() {
    setProgress((prevState) => (prevState += 5));
  }

  const callback = useCallback((event) => {
    event.preventDefault && event.preventDefault();
    event.stopPropagation && event.stopPropagation();
    event.cancelBubble = true;
    console.log("long pressed!");
  }, []);

  const longPressEvent = useLongPress(callback, {
    onStart: (event) => {
      console.log("On Start");
      event.preventDefault && event.preventDefault();
      event.stopPropagation && event.stopPropagation();
      event.cancelBubble = true;
      progressTimer.current = setInterval(handleTime, 100);
    },
    onFinish: (event) => {
      console.log("On finish");
      event.preventDefault && event.preventDefault();
      event.stopPropagation && event.stopPropagation();
      event.cancelBubble = true;
      setProgress(0);
      clearInterval(progressTimer.current);
    },
    onCancel: (event) => {
      console.log("On cancel");
      event.preventDefault && event.preventDefault();
      event.stopPropagation && event.stopPropagation();
      event.cancelBubble = true;
      setProgress(0);
      clearInterval(progressTimer.current);
    },
    threshold: 2000,
    captureEvent: true,
    cancelOnMovement: false,
    detect: "both"
  });

  let content = (
    <div className="content-center">
      {progress}
      <Item
        events={longPressEvent}
        name="name"
        image="file.png"
        progress={progress}
      />
    </div>
  );

  return <React.Fragment>{content}</React.Fragment>;
}

export default App;

Item.js

import React from "react";
import "./Item.css";
import VerticalProgress from "./VerticalProgress";
import faker from "faker";

export default function Item(props) {
  return (
    <div className="flex justify-center w-full disable-select">
      <div
        className="float-left absolute z-50 w-full disable-select"
        style={{ height: 500 }}
        {...props.events}
      >
        <div></div>
      </div>
      <VerticalProgress className="z-0" progress={props.progress} />
      <img
        className="z-0 disable-select"
        src={faker.image.image()}
        alt={props.name}
        height="200"
        id="ItemImage"
      />
    </div>
  );
}

我的问题是:如何防止在Firefox桌面移动测试模式中提前调用onCancel?如果它在那里发生,它必然会发生在其他浏览器中,例如 Safari 或实际的 Firefox 移动版。即使不是,这也是一个非常意想不到的副作用,并且使移动测试变得困难。

第二个问题:是什么原因造成的

IndexSizeError: Selection.getRangeAt: 0 is out of range

错误?

这是模拟器端的错误。在手机上,它可以正常工作。

TL;DR

这个问题似乎与 Touch emulation 有关(任何屏幕 size/device 都会发生)。启用后,触发的事件从 onMouseDown/onMouseStart 更改为 onTouchStart/onTouchEnd,并且它们的行为也会发生变化。默认情况下,几分之一秒后 Firefox 打开上下文菜单(您可以在 'Open Sandbox' 按钮上测试默认行为),这将结束触摸并触发 onTouchEnd(以及 onMouseMove).

奇怪:无论我尝试过什么都不会阻止触摸结束(但会阻止菜单显示)。

话虽这么说,我已经在移动设备上测试了您的代码(Android 上的 Firefox 91.4.0 - 3 台设备 - 2 家供应商)并且一切 工作正常 . This is my code

根据我的观察,移动设备上没有上下文菜单,除了像 <img><a> 这样的少数元素,它们有自己的菜单(复制 link)从来没有能够删除。但在任何情况下(即使出现弹出菜单)useLongPress 都按预期工作。

备注

不要混合使用 React 等框架和原始 DOM 函数(如 addEventListener())。您在 index.html 中添加的代码无法按预期工作。做这样的事情:

const __absorb = useCallback((event) => {
  event.preventDefault && event.preventDefault();
  ...
  return false;
}, []);

<a onContextMenu={__absorb}>