Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use window.history.pushState 'safely'

Tags:

I would like to use the window.history.pushState() function in supporting browsers. Unfortunately I'm getting an error on Firefox:

TypeError: history.pushState is not a function

How is it possible to avoid that?

like image 444
Roch Avatar asked Feb 17 '11 14:02

Roch


People also ask

Does history pushState refresh the page?

The history. pushState() method can be used to push a new entry into the browser's history—and as a result, update the displayed URL—without refreshing the page. It accepts three arguments: state , an object with some details about the URL or entry in the browser's history.

What does the pushState () method do?

The pushState() method enables mapping of a state object to a URL. The address bar is updated to match the specified URL without actually loading the page.


2 Answers

Although I haven't tested it in JavaScript, I know in other languages that try-catch is more resource intensive than a simple if...

Use:

if(history.pushState) {
    history.pushState({"id":100}, document.title, location.href);
}

Keep in mind that when you click the back button, nothing actually happens unless you implement window.onpopstate. You'll need to pass in the data you need to grab the content:

if(history.pushState && history.replaceState) {
    //push current id, title and url
    history.pushState({"id":100}, document.title, location.href);

    //push new information
    history.pushState({"id":101}, "new title", "/new-url/");

    //this executes when you use the back button
    window.onpopstate = function(e) {
        alert(e.state.id);
        //perhaps use an ajax call to update content based on the e.state.id
    };
}
like image 100
Levi Morrison Avatar answered Sep 22 '22 22:09

Levi Morrison


[try-catch] tag implies what you know the answer already... (is there anything more specific?) The other possibitity is to check if ( history.pushState ) history.pushState( {}, document.title, location.href );

like image 41
Free Consulting Avatar answered Sep 21 '22 22:09

Free Consulting