我使用history.pushState
并且它就像一个魅力,除了一个问题,如果你在chrome或firefox中点击“返回”后正确操作了网址,则网址会更改,但页面不会重新加载。
详细说明:
我们从mysite.tld
现在(在一些用户互动之后),我们使用history.pushState
并将网址更改为mysite.tld/some/subpage
。页面会相应地重新呈现。
现在,如果您点击“返回”,则网址会更改,但不会显示页面! 如果刷新,页面将刷新。
我的天真(我是一个绝对的javascript noob)是添加一个eventListener:
dom.window.addEventListener("popstate",
{
(event: Event) =>
{
dom.window.location.reload()
}
})
但当然这有一些令人不快的副作用(每当网址更改时,它会重新加载页面。非常糟糕,例如画廊或幻灯片)
答案 0 :(得分:1)
pushstate功能允许您在浏览器历史记录(URL,标题)中反映客户端应用程序的状态。
这是流程
popstate
事件
state
属性,该属性是您在推送状态时设置的数据看看这个例子(评论说明):
<强> popstate.html 强>
<!DOCTYPE html>
<html>
<head>
<title>Pushstate/Popstate</title>
</head>
<body>
<a href="javascript: void(0)">increment</a>
<div id="output">?</div>
<script type="text/javascript">
window.onload = function() {
let identifier = 0,
match,
query,
identifiererEl = document.getElementById("output");
// - Since all URL properties can be accessed clientside,
// the request data is extracted from the current URL.
// - This can be seen like an ID that the server may use
// to find the actual content
// - Note that history.state makes no sense in this case,
// since it is null when the script first runs.
match = /identifier=(\d+)/.exec(location.search);
// This emulates the behaviour of a server it won't make sense in
// a client side application
if (match) {
// Set the identifier with the data "from the server"
identifier = Number(match[1]) || 0;
// Make the view initially reflect the state
render(identifier);
}
function render(text) {
identifiererEl.textContent = text;
}
// Listen to user interaction to alter the data, render and
// push the state
document.querySelector("a").addEventListener("click", (e) => {
// Increment only for simplicity
identifier++;
render(identifier);
history.pushState(
{ identifier: identifier },
"",
`/popstate.html?identifier=${identifier}`
);
});
// Listen to state changes to update the view
window.addEventListener("popstate", (e) => {
// Here you'd determine the actual data to render.
// For simplicity the identifier itself is rendered.
render(e.state.identifier);
});
};
</script>
</body>
</html>
说到图库示例,identifier
可能是照片ID,render()
可以更新图片来源。当然,您负责获取所有或下一张/上一张照片(通过AJAX或内联到页面源中)。