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

前端 未结 3 1522
梦谈多话
梦谈多话 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:24

    A shim does exist for the History API. The History.js uses HTML4’s hashchange event with document fragment identifiers to mimic the history API in older browsers. If one of the hash URLs is used by a modern browser, it uses replaceState to quietly correct the URL.

    If you're not bothered about it not working in older browsers and you just want to use it without throwing an error, I do this...

    window.history && window.history.pushState && window.history.pushState("", "", url);
    

    This checks that history and the pushstate function exist before trying to use it.

提交回复
热议问题