popstate event on history api does not fire - javascript

I have a simple code to test the history api of html5
Just some buttons
<button name="hey1" onClick="historytestone();">history test one</button>
<button name="hey2" onClick="historytesttwo();">history test two</button>
<button name="hey3" onClick="historytestthree();">history test three</button>
<button name="hey4" onClick="historytestfour();">history test four</button>
<button name="hey5" onClick="historytestfive();">history test five</button>
and my js is like
function historytestone(){
history.pushState({page: "ross"}, "ross","ross.html");
}
function historytesttwo(){
history.pushState({page: "monica"}, "monica","monica.html");
}
function historytestthree(){
history.pushState({page: "chandler"}, "chandler","chandler.html");
}
function historytestfour(){
history.pushState({page: "joy"}, "joy","joy.html");
}
function historytestfive(){
history.pushState({page: "rachel"}, "rachel","rachel.html?a=1&b=2");
}
// this does not work
window.addEventListener("popstate", function(event) {
alert("hello");
});
//nor this works
window.onpopstate=function(event){
alert("hello");
}
When I try to listen for the popstate event, I get no alert and no errors on the console. No metter what syntax I use, I get nothing.
Sorry, but I cannot see what is wrong. Please explain.
EDIT
Here is my problem.
This is my code here and this is the demo I was based here.
Now, I believe that my code is a simplified version of the demo.
I have to click the "back" button of the browser in order to fire the popstate event (see the alerts). But the demo can fire the popstate event (change content) just by clicking the names.
Why this happens? Why I have to hit the back button and the demo does not, even tho is the same code? Thanks again

based on the definition here: https://developer.mozilla.org/en-US/docs/Web/Events/popstate
The popstate event is fired when the active history entry changes. If
the history entry being activated was created by a call to
history.pushState() or was affected by a call to
history.replaceState(), the popstate event's state property contains a
copy of the history entry's state object.
Note that just calling history.pushState() or history.replaceState()
won't trigger a popstate event. The popstate event is only triggered
by doing a browser action such as a click on the back button (or
calling history.back() in JavaScript).
Browsers tend to handle the popstate event differently on page load.
Chrome and Safari always emit a popstate event on page load, but
Firefox doesn't.
if you see the source code of http://html5doctor.com/demos/history/ each time when you click a link it calls the updateContent function (which is also the event handler of popstate) then it calls pushState.

Related

Call history.back() without triggering 'popstate'

Is there a way to call window.history.back(); without triggering this.getWindow().on('popstate', this.handleBrowserButtons.bind(this));?
No, window.history.back and window.history.go would always trigger the popstate event.
In fact, that's the only time the event is actually triggering so you could probably remove the popstate event handler altogether and use something else if you don't want this happening on back/forward navigation.
As history.back and history.go always call a registered onpopstate event you could make the onpopstate event the main way of closing the modal. I did this when I was doing something similar and it worked well.
To keep this backward compatible with browsers that don't support pushstate you can check for support and call closeModal directly when there is no support.
So the close modal button code would be like this:
if (history.pushState) {
// Your popstate event handler will be called, which calls closeModal()
history.back();
}
else {
// No popstate event handler registered, so call closeModal() directly
closeModal();
}

how to cancel window.print(); on click on the Print button, Print pop up but no print action

I want to have the window.print() pop up but when User clicks on Print button, it is not windows print but onclick or window.onbeforeprint I wish to trigger my own personalised print function.
As such, on click Print, I need to cancel the print action and trigger my personalised() function.
Please help how to cancel window.print(); on click on the Print button
You can achieve this by simply using the preventDefault().
What Event.preventDefault() does is
The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. The event continues to propagate as usual, unless one of its event listeners calls stopPropagation() or stopImmediatePropagation(), either of which terminates propagation at once.
You can read more at Event.preventDefault() from MDN Web Docs
From your post, it looks like you are not referencing any JavaScript libraries (such as jQuery)... so a straight up JavaScript approach would be:
document.querySelector("#printLink").addEventListener("click", function(event) {
event.preventDefault();
//your printing related window code etc.
}, false);
If, however, you are using a JavaScript library and it happens to be jQuery, then the following will be what you are looking for--
jQuery("#printLink").click(function(e) {
e.preventDefault();
//your printing related window code etc.
});
jQuery event.preventDefault()
In either case, your print link would look like:
<a id="printLink" ...></a>
(Notice the ID attribute in the anchor element)

How to "browser back" when using pushState?

I have this code:
window.history.pushState(newUrl, "", newUrl);
My question is, how to make sure that when doing pushState the browser back button will function as normal or in other words should go "back"?
(without using jQUery)
The normal behaviour for the back button is for the browser to go back to the previous document, but when you use pushState, there isn't a previous document.
The point of pushState is to keep the browser on the same document while updating the URL. This is accompanied by DOM changes applied with JavaScript.
It is a simulation of going to a new page.
To make the back button appear to work, you need to write a matching simulation of going to the previous page.
You can do this by listening for a popstate event.
Page <span id="p">1</span>
<button>Next</button>
<script>
document.querySelector("button").addEventListener("click", function () {
document.getElementById('p').textContent++;
history.pushState({}, "", "/" + document.getElementById('p').textContent);
});
addEventListener("popstate", function (e) {
document.getElementById('p').textContent--;
e.preventDefault();
});
</script>
push is for pushing... adding
you should go for history.back()
If you want to popState - emit popstate event on window or do history.replaceState()
If you want to cancell commented event:
My answer will do the trick
https://stackoverflow.com/a/44553087/5694206

Is there a way to delay a popstate event?

I've tried a few methods to see if I can create a cross browser solution for delaying a popstate event but have not had any luck.
Anyone have any ideas or thoughts?
Below obviously does not work, but something to the effect of:
$(window).on('popstate', function(e) {
// something here to delay the history pageload
console.log('a wild console has appeared!');
});
So the flow would follow this sequence:
Browser "back" or "forward" button clicked
run initial code
A delay before the page changes
page change
According to the Documentation the popstate event is
only triggered by doing a browser action such as a click on the back button
So I do not believe it will get triggered when user clicks 'forward' (and it varies in some browsers)
For reference, here's the full text:
The popstate event is fired when the active history entry changes. If the history entry being activated was created by a call to history.pushState() or was affected by a call to history.replaceState(), the popstate event's state property contains a copy of the history entry's state object.
Note that just calling history.pushState() or history.replaceState() won't trigger a popstate event. The popstate event is only triggered by doing a browser action such as a click on the back button (or calling history.back() in JavaScript).
Browsers tend to handle the popstate event differently on page load. Chrome (prior to v34) and Safari always emit a popstate event on page load, but Firefox doesn't.
UPDATED ANSWER ABOVE
Your code works. (see below) - I added an element to trigger the event (you can see the results in the console)
Make sure you include the jQuery library on your HTML prior to using it though.
$(window).on('popstate', function(e) {
console.log('fired instantly!');
var timer = setTimeout(function() {
console.log('delayed popstate!');
clearTimeout(timer);
}, 1000);
});
$(window).trigger( 'popstate') ;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

popstate event handler seems not to work

I'm having a problem with a 'popstate' event handler, this is my code:
window.addEventListener("popstate", function (event){
if (event.state) {
alert('abc')
}
});
// The data object is arbitrary and is passed with the popstate event.
var dataObject = {
createdAt: '2011-10-10',
author: 'donnamoss'
};
var url = '/posts/new-url';
history.pushState(dataObject, document.title, url);
I expected this code will pop up an alert box when it's executed but, nothing happens.
Is there anything wrong here?
Thank you.
pushState do not trigger the popstate event, only clicking back / forward button (or use backspace) or invoking history.back() / history.go(n) would trigger this event.
Also, in webkit browsers, a popstate event would be triggered after page's onload event, but Firefox and IE do not have this behavior.
No it will not,
As per MDN documentation
Note that just calling history.pushState() or history.replaceState() won't trigger a popstate event. The popstate event is only triggered by doing a browser action such as a click on the back button (or calling history.back() in JavaScript).
Again as per this question the popstate event is not triggered in Chrome when you call pushState().
history.pushState() will not trigger the popstate event by definition.
The popstate event is fired in certain cases when navigating to a session history entry.
This event is intended to be only triggered when navigating to a history entry, either by pressing the back/forward button, or history.go/back.

Categories