Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.history.back illegal invocation

Why is it that I can do this:

$("button").on('click', function(){window.history.back();});

however, when I try;

$("button").on('click', window.history.back);
/*or*/ $("button").on('click', history.back);

I get:

Uncaught TypeError: Illegal invocation
at HTMLAnchorElement.dispatch (jquery-1.12.4.js:5226)
at HTMLAnchorElement.elemData.handle (jquery-1.12.4.js:4878)

I was under the impression that when there is no retained context it defaults to the window object, which would allow me to do this?

like image 356
Zze Avatar asked Oct 22 '17 21:10

Zze


1 Answers

First of all, history.back() must be invoked with history as the context, if it defaults to window it will throw the error you describe. The issue here though is that jQuery invokes the handler with the element that has the event listener bound.

Your first line of code works because context is irrelevant to the anonymous function you pass as a handler. The fact that jQuery sets the element as the context doesn't matter since you correctly invoke history.back() inside of it.

like image 152
Lennholm Avatar answered Oct 02 '22 22:10

Lennholm