【发布时间】:2021-08-05 15:36:58
【问题描述】:
我有以下 HTML,它来自 GET /home,并使用 Javascript 劫持表单提交事件,以便将方法从 POST 更改为 DELETE。服务器侦听对DELETE /delete 的请求,它实际上返回一个303 重定向到GET /new,它提供一些HTML。 Javascript 使用历史 API 将地址栏更新为 example.com/new,并使用 window.document.documentElement.innerHTML = text 呈现 HTML。这一切都可以找到,当我单击后退按钮时,地址栏确实会更改回之前的地址(example.com/home),但不会呈现 HTML。为什么是这样?我已经阅读了Mozilla docs,但我找不到任何关于不呈现 HTML 的内容,如果后退按钮更新地址栏,页面应该更新到那个 URL 吗?我也尝试过使用history.replaceState(),但没有成功。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<form action="/delete" method="POST">
<input type="submit" value="submit" />
<input name="key" value="val" />
</form>
</body>
<script>
const form = document.querySelector("form");
form.addEventListener("submit", async e => {
e.preventDefault();
console.log(new URLSearchParams(new FormData(e.currentTarget)));
const response = await fetch(form.action, {
body: new URLSearchParams(new FormData(e.currentTarget)),
method: "DELETE",
redirect: "follow",
});
const text = await response.text();
history.pushState({}, "", response.url);
// history.replaceState({}, "", response.url);
window.document.documentElement.innerHTML = text;
});
</script>
</html>
【问题讨论】: