Search code examples
javascriptecmascript-6windowdom-eventsaddeventlistener

JavaScript: Window EventListener not working


I add the following event listener to the window object:

window.addEventListener( 'popstate beforeunload', () => {
    console.log('test');
});

I'd expect that a console log entry is being created whenever I navigate the browsers history or reload the page. However, nothing happens. What am I doing wrong?


Solution

  • If you want two event listeners, you need to add them separately.

    var handler = () => {
      console.log('test');
    };
    window.addEventListener('popstate', handler);
    window.addEventListener('beforeunload', handler);
    

    Some libraries like jQuery's .on will automatically split on whitespace to allow this kind of thing, but .addEventListener itself does not.