What are the differences between history.pushState & location.hash?

前端 未结 8 1383
既然无缘
既然无缘 2020-11-30 03:29

I\'m trying to update the URL using window.location.hash or history.pushState.

What are the differences and advantages of each method?

8条回答
  •  暖寄归人
    2020-11-30 03:51

    location.hash has a better support than the history.pushState method.

    The advantage of the pushState method is that you can bind a state to the history entry.

    If you don't need this state object, I recommend to use the location.hash property, to have better compatibility with older browsers.

    location.hash = 'new-hash';
    console.log(history.state); // null or undefined
    
    history.pushState({extraData: "some state info"}, '', 'new-hash'); //<---
    console.log(history.state); // [object Object] = {"extraData": "some state info"}
    

提交回复
热议问题