【问题标题】:preventDefault, stopPropagation, and cancelBubble not enough to prevent contextMenu from trying to open in Firefox mobile test viewpreventDefault、stopPropagation 和 cancelBubble 不足以阻止 contextMenu 尝试在 Firefox 移动测试视图中打开
【发布时间】:2021-10-27 12:36:37
【问题描述】:

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

如果您在常规桌面视图或 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>
  );
}

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

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

IndexSizeError: Selection.getRangeAt: 0 超出范围

错误?

【问题讨论】:

  • 相同的测试,相同的平台,您的代码。这里没有问题
  • 你有插件或鼠标扩展吗?
  • 您使用的是响应式模式吗?我已将我的设置为 Galaxy S9,并且在没有插件或扩展的私人窗口中它仍然会发生

标签: javascript html css reactjs firefox


【解决方案1】:

这是模拟器方面的错误。在移动设备上,它可以正常工作。

TL;DR

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

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

话虽如此,我已经在移动设备(Android 上的 Firefox 91.4.0 - 3 个设备 - 2 个供应商)上测试了您的代码,并且一切正常运行This is my code

根据我的观察,移动设备上没有上下文菜单,除了 &lt;img&gt;&lt;a&gt; 等少数元素,它们有自己的菜单(复制链接),我从未能够删除。但无论如何(即使出现弹出菜单)useLongPress 都能正常工作。

注意事项

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

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

<a onContextMenu={__absorb}>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-27
    • 1970-01-01
    • 2015-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多