Mark event as explicitly NOT passive

2020-04-19 05:27发布

[Violation] Added non-passive event listener to a scroll-blocking 'wheel' event. Consider marking event handler as 'passive' to make the page more responsive.

This warning is kinda getting on my nerves to be honest. I have an event where I sometimes need to call preventDefault()

Is there a way to mark the event as explicitly NOT passive and to get rid of this warning? I know it doesn't hamper execution flow, but it's an annoyance. All I can find is how to mark it passive, but it's a desktop app, which doesn't need the passive marker for scroll optimization.

I'm not sure what chrome thought when they implemented this as default warning to clutter up the dev console. I feel like it's something like the agree button now on EULAS, don't read, just click ok, cookie warning, just click ok... I don't wish to fix it, I wish to ignore it, consiously.

enter image description here

2条回答
Melony?
2楼-- · 2020-04-19 06:08

Specify passive: false when you add the listener:

el.addEventListener('click', someFn, { passive: false });

See: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

查看更多
走好不送
3楼-- · 2020-04-19 06:10

The above solution works but requires a change to each call to addEventListener.

If you would prefer to silence the warnings through a single change that impacts all calls to addEventListener that you've already written in old form, you can do something like the following (modified from https://stackoverflow.com/a/49292829/3160967). You can further modify this if you want it to selectively handle / report / etc.

var addEventListener_orig = EventTarget.prototype.addEventListener;
EventTarget.prototype.addEventListener = function(type, handler, opts_orig) {
  var opts;
  if(opts_orig === false || opts_orig === true)
    opts = { capture: opts_orig, passive: false };
  else if(!(opts_orig && opts_orig.constructor == Object))
    opts = { passive: false };
  else
    opts = opts_orig;

  arguments[2] = opts;
  return addEventListener_orig.apply(this, arguments);
};

Please note, as this modifies the base object, third party libraries might act differently (though I cannot think of any scenario where that could actually happen, unless the 3p library would also monkey patch addEventListener, as the above, if I'm not mistake, just fills in the default values that otherwise get used when none were explicitly provided, and by doing so makes the warning go away)

查看更多
登录 后发表回答