Tag Archives: Unable to preventDefault inside passive event listener due to target being treated as passive

Unable to preventDefault inside passive event listener due to target being treated as passive?

This is a reprint of the original text https://blog.csdn.net/lijingshan34/article/details/88350456

Chrome monitors touch events and reports errors: unable to passively listen for events preventdefault, which is an error reported by the new version of Chrome browser

Description: let’s talk about the ghost of preventdefault(), which cancels the default event. If this function works, such as the default form submission and the click and jump of a link, it won’t work
reason: changes made by Google browser in order to quickly respond to touch events
History: when the browser first responds to the default event, check whether the default event has been cancelled. In this way, there is a slight delay before responding to the sliding operation
now: Google has decided to cancel the check of this event by default, and the default time is cancelled. The sliding operation is performed directly. So it’s smoother<However, the console of the browser will remind you of the error

Specific situation:
starting from chrome 56, the touchstart and touchmove event handling functions registered in window, document and body will default to passive: true. The browser ignores preventdefault() to scroll for the first time

The results are consistent as follows:

wnidow.addEventListener('touchmove', func) The effect is the same as the following sentence
wnidow.addEventListener('touchmove', func, { passive: true })

New problems arise:

if e.preventDefault () is invoked in the touchstart and touchmove event handlers of the above 3 elements, it will be ignored by the browser and will not prevent the default behavior. Strong>
you can test it:

body {
    margin: 0;
    height: 2000px;
    background: linear-gradient(to bottom, red, green);
}

// In chrome56, it scrolls as usual, and the console will prompt that, blablabla
window.addEventListener('touchmove', e => e.preventDefault())

So what should we little programmers do

We can do this:

that is, the console will not prompt, and preventdefault() will work
two schemes:
1. When registering a processing function, it is explicitly declared that it is not passive
window.addeventlistener (‘touchmove ‘, func, {passive: false})

2. Apply the CSS property touch action: none; In this way, any touch event will not generate default behavior, but the touch event will still trigger for details, please refer to: touch action
– – –
copyright notice: This is an original article of CSDN blogger “Li Jingshan – Programmer”, which follows CC 4.0 by-sa copyright agreement. Please attach the link of the original article and this notice