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

匿名 (未验证) 提交于 2019-12-03 02:44:02

问题:

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?

回答1:

[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 );



回答2:

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


回答3:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!