Javascript 我怎样才能“安全地”使用 window.history.pushState
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5030564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use window.history.pushState 'safely'
提问by Roch
I would like to use the window.history.pushState()
function in supporting browsers. Unfortunately I'm getting an error on Firefox:
我想window.history.pushState()
在支持浏览器中使用该功能。不幸的是,我在 Firefox 上遇到错误:
TypeError: history.pushState is not a function
类型错误:history.pushState 不是函数
How is it possible to avoid that?
怎么可能避免这种情况?
采纳答案by Free Consulting
[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 );
[try-catch] 标签暗示你已经知道答案......(还有什么更具体的吗?)另一种可能性是检查 if ( history.pushState ) history.pushState( {}, document.title, location.href );
回答by Levi Morrison
Although I haven't tested it in JavaScript, I know in other languages that try-catch is more resource intensive than a simple if...
虽然我没有在 JavaScript 中测试过它,但我知道在其他语言中,try-catch 比简单的 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:
请记住,当您单击后退按钮时,除非您实现window.onpopstate
. 您需要传入获取内容所需的数据:
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
};
}
回答by herostwist
A shim does exist for the History API. The History.jsuses 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.
History API 确实存在垫片。该History.js使用HTML4的hashchange事件与文档片段标识符模仿历史API中的旧版浏览器。如果现代浏览器使用了其中一个哈希 URL,它会使用 replaceState 悄悄地更正 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.
这会在尝试使用它之前检查历史记录和 pushstate 函数是否存在。