无法删除所有事件侦听器

E23*_*235 2 javascript event-listener

我正在尝试从某个网站上删除事件侦听器,但没有成功。

这是来自网站的事件侦听器:
在此处输入图片说明

有一个 javascript 脚本可以创建这些事件:

document.addEventListener('contextmenu', function (ev) {
        ev.preventDefault();
    }
)
Run Code Online (Sandbox Code Playgroud)

我试图用以下方法删除它:

document.removeEventListener('contextmenu', function (ev) {
                ev.preventDefault();
            }) 
Run Code Online (Sandbox Code Playgroud)

我也试过:

(getEventListeners(document)).contextmenu = null
Run Code Online (Sandbox Code Playgroud)

但它没有用,我想是因为我使用了一个不同的新功能。

有没有办法清除所有事件?

参考:
无法删除事件侦听器

syn*_*t1c 5

您需要指定绑定到的函数 removeEventListener

您可以通过创建一个函数并传递到两个参考做到这一点addEventListenerremoveEventListener

// create a function
function onRightClick(ev) {
  ev.preventDefault();
  console.log('onRightClick')
}

// pass the function to both add and remove
document.addEventListener('contextmenu', onRightClick)
document.removeEventListener('contextmenu', onRightClick)
Run Code Online (Sandbox Code Playgroud)

这是一个完整的示例,它将所有事件缓存到元素中,允许您删除特定事件,所有事件类型的所有事件。

它还有一个 MutationObserver 观察 DOM 的变化,如果一个元素被移除,那么附加到它的事件也会被移除。

const Events = (() => {
  
  const cache = new Map
  
  const observer = new MutationObserver(function(mutations) {
    for (let mutation of mutations) {
      if (mutation.type === 'childList') {
        if (mutation.removedNodes.length) {
          console.log('element removed from the dom, removing all events for the element')
          mutation.removedNodes.forEach(x => Events.remove(x))
        }
      }
    }
  })
  
  // watch the dom for the element being deleted
  observer.observe(document.body, { childList: true })
  
  return {
  
    add(el, type, fn, capture = false) {
      let cached = cache.get(el)
      if (!cached) {
        cached = {}
        cache.set(el, cached)
      }
      if (!cached[type]) {
        cached[type] = new Set
      }
      cached[type].add(fn)
      el.addEventListener(type, fn, capture)
    },
    
    remove(el, type, fn) {
      const cached = cache.get(el)
      if (!cached) {
        return false
      }
      // remove all events for an event type
      if (type && !fn) {
        cached[type].forEach(fn => {
          el.removeEventListener(type, fn)
        })
        cached[type] = new Set
      }
      // remove a specific event
      else if (type && fn) {
        el.removeEventListener(type, fn)
        // remove the event from the cache
        cached[type].delete(fn)
      }
      // remove all events for the element
      else {
        for (key in cached) {
          cached[key].forEach(fn => {
            el.removeEventListener(key, fn)
          })
        }
        cache.delete(el)
      }
    },
    
    show(el, type) {
      const cached = cache.get(el)
      if (!cached) {
        return false
      }
      if (type) {
        return cached[type]
      }
      return cached
    }
  }
})()

function onRightClick() {}

Events.add(document, 'contextmenu', onRightClick)
Events.remove(document, 'contextmenu', onRightClick) // remove a specific event callback
Events.remove(document, 'contextmenu') // remove specific event types from an element
Events.remove(document) // remove all events from an element


const testElement = document.querySelector('#test_element')

Events.add(testElement, 'click', function deleteSelf(e) {
  this.parentNode.removeChild(this)
})
Run Code Online (Sandbox Code Playgroud)
<div id="test_element">
  when you <strong>click me</strong> I will be deleted from the DOM which will fire the MutationObserver to remove all my events
</div>
Run Code Online (Sandbox Code Playgroud)