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

前端 未结 3 1590
梦谈多话
梦谈多话 2021-01-31 05:01

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

TypeError

3条回答
  •  情书的邮戳
    2021-01-31 05:31

    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
        };
    }
    

提交回复
热议问题