我使用document.open() + write() + close()从客户端创建一个新页面。这是可行的,但它将用新页面替换当前的历史元素,因此当用户单击返回时,他们不会看到他们刚刚访问的页面。例子:
- 首页
- 点击按钮导航到以下页面。
- 点击该页面的点击我按钮。
- 点击返回-这会使用户返回到我不想要的主页。
我试过用history.pushState()
插入历史元素,但这也不起作用。它允许文档。打开页面有一个新的url。点击返回将用户返回到我想要显示的页面的URL,但它仍然是"新页面"。
完整的HTML页面代码如下。这种类型的示例不能在fiddles中工作,但可以在本地进行测试。
<html>
<body>
<button onclick="clickme()">Click me</button>
<script>
function clickme() {
history.pushState(null, null, "Results/");
document.open("text/html");
document.writeln("New Page");
document.close();
}
</script>
</body>
</html>
注意:寻找跨浏览器支持的解决方案,包括最新的Chrome 45,它可能已经加强了安全性。
我确实找到了一个解决方案,但仍然不是我想要的。
function clickme() {
results = window.open();
results.document.writeln("New Page");
results.document.close();
}
这显然会创建一个全新的选项卡/窗口来显示结果,而不是在当前选项卡的历史记录中新建一个页面。这在手机中几乎是相同的,因为返回会将您带回到原始页面,但在桌面浏览器中则不是。
我会为第3页创建一个实际的网页,而不是推送虚假的历史事件。
历史。在旧的IE(9及以下)中不支持pushState,并且在某些android上有bug,这可能不是您项目的问题。http://caniuse.com/搜索= history.pushState
如果你不能改变后端重定向到第3页,你可以在javascript中这样做:
- 将html保存在localStorage 中
- 重定向到第3页
- 当第3页加载时插入你的html。
function clickme() {
var html = 'my generated html';
localStorage.savedHtml = html;
window.location = 'page3.htm';
}
3页:
<html>
<head>
<!-- I'm assuming you're using jquery -->
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<div id="restoredHtml"></div>
<script>
$(function(){
var savedHtml = localStorage.savedHtml || 'No html to restore';
$('#restoredHtml').html(savedHtml);
localStorage.removeItem('savedHtml');
});
</script>
</body>
</html>
您可以将字符串对象存储在pushState中,然后读取该对象的值,以便您可以根据该值而不是浏览器流构建页面。
所以首先我们用pushState() 添加一个新元素var markup = "New page content";
history.pushState( { pageContent : markup } , null, "Results/");
document.open("text/html");
//Write the markup using document object
document.writeln(markup);
document.close();
那么你可以在onpopstate事件上附加一个监听器,并检查state是否有pageContent,如果有,那么从它构建文档:
window.onpopstate = function(event) {
if(event.state.hasOwnProperty("pageContent")){
document.open("text/html");
//Write the markup using document object
document.writeln(event.state.pageContent);
document.close();
}
};
是否有特定的原因需要使用document ?开放、文档。写和记录。关闭?保留一个可以维护状态的页面,并交换标记,这不是更容易吗?
下面的代码可以让你在Chrome中使用前进和后退按钮:
<body>
<div id="content-area">
</div>
<button onclick="clickme()">Change Page</button>
<script>
var state = 1;
function changeContent(state) {
var contentArea = document.getElementById("content-area");
contentArea.innerHTML = "Page " + state;
}
function clickme() {
state = state+1;
history.pushState(state, null, "/Page" + state + "/");
changeContent(state);
}
window.onpopstate = function(event) {
if (event.state != null) {
state = event.state;
} else {
state = 1;
}
changeContent(state);
};
changeContent(state);
</script>
</body>