Search code examples
javascriptpreventdefaultevent-bubblingstoppropagation

How does stopPropagation cancel preventDefault?


I have a website that does not allow to open up the context menu by clicking the right button on a mouse.
It seems like the website does blocking it by using preventDefault on the event oncontextmenu.
I was able to bypass it by

window.addEventListener('contextmenu', (event) => {
    event.stopPropagation();
}, true)

I know that preventDefault blocks the default action of an event and stopPropagtion prevents an event from firing bubble to its parent element. But how does stopPropagation cancel preventDefault?


Solution

  • By calling stopPropagation you stop other attached event listeners from capturing the event. Thus, the event listener that would call preventDefault would not capture it and thus would not prevent the context menu from opening.

    See in the example below. The listener that tries to prevent the context menu from opening is not executed because stopPropagation is called:

    window.addEventListener('contextmenu', (event) => {
        console.log('stopPropagation')
        event.stopPropagation();
    }, true)
    
    
    document.body.addEventListener('contextmenu', (event) => {
      console.log('stop context menu')
      event.preventDefault();
    })
    Right click
    <br/>
    <br/>
    Notice that 'stop context menu' is not logged