Js prohibits dragging pictures to the browser to open the event by default

Recently, I am developing a demo that scans the barcode of a product with a barcode scanner to create a product , which uses dragging and dropping pictures to the browser to upload. During the use, the user accidentally dragged and dropped it to a page other than the upload component , which triggered the default behavior of the browser, automatically opened the webpage and opened the picture, and the entire operation process would freeze, causing very bad results. experience. At this point, you need to use the principle of bubbling/digging to disable the browser's default event of opening pictures.

The page looks like this:

The upload uses the upload component of antd combined with the Form form.

We can use addEventListener and removeEventListener to bind and remove event listeners for the entire page.

1. First define a function that prevents the default event:

 // 阻止默认事件Function
  forbidDefaultEvent = (e) => {
    e.preventDefault();
  }

2. Then add a listener to the page move event after the page is rendered:

componentDidMount = async () => {
    // 禁止浏览器打开拖拽的图片
    document.addEventListener('drop', this.forbidDefaultEvent, false);
    document.addEventListener('dragover', this.forbidDefaultEvent, false);
};

3. Finally, remember to unlisten when the page leaves:

componentWillUnmount = async () => {
    document.removeEventListener('drop', this.forbidDefaultEvent, false);
    document.removeEventListener('dragover', this.forbidDefaultEvent, false);
};

This perfectly prevents the browser from opening pictures by default.

Guess you like

Origin blog.csdn.net/qq_42348464/article/details/123728717