在浏览器页面中移动 "sideways" 而不添加到浏览器历史记录

Move "sideways" through browser pages without adding to browser history

问题:

点击下一章时必须执行的Javascript 有效地从浏览器历史记录中删除当前章节页面,然后转到新章节页面历史堆栈看起来好像用户从书页来到了新章节页?

努力:

我推荐你使用 history 包。

您的代码将如下所示

import { createBrowserHistory } from "history"
const history = createBrowserHistory()

然后下一章你将使用history.replace("/url/to/your/next/chapter")。 如果用户从书页转到第一章,那么接下来的每一章都会替换当前位置,这意味着之前的位置将参考 Book。 这意味着对于 Back 你将使用 history.goBack().

希望对您有所帮助!

据我了解,您无法使用历史记录对象,因为如果他们跳转章节并按下后退页面,他们将返回到点击后退页面之前的位置,而不是后退页面。

解决这个问题的方法是将章节页面保存在一个数组中 E.G

let currentPage = 0;
let currentChapter = 0;
let totalPages = 97;
let chapters = [0,3,25,51,63]

let nextPage = () => {
    if(currentPage+1 > totalPages) return;
    currentPage++;
    if(currentPage > chapters[currentChapter]){
        currentChapter++;
    }
}
let prevPage = () => {
    if(currentPage == 0) return;
    currentPage--;
    if(currentPage < chapters[currentChapter]){
        currentChapter--;
    }
}
let nextChapter = () => {
    if(currentChapter+1 > chapters.length) return;
    currentChapter++;
    currentPage = chapters[currentChapter]
}
let previusChapter = () => {
    if(currentChapter == 0) return;
    currentChapter--;
    currentPage = chapters[currentChapter]
}

有了这个,你可以使用pushState根据方法sll中的currentPage改变URL,然后你可以从currentPage计算出currentChapter在页面加载时,这将允许进行刷新。

这就是我最终所做的,感谢 Limbo 的启发。来自下一个或上一个 link 的 onclick 事件调用此函数:

function sidewaysLink()
{
    history.replaceState({}, "", this.getAttribute("href"));
    history.go(0);
    return false;
}

不知道为什么我花了这么多的错误才弄清楚这个问题。操作很简单:history.replaceState() 替换浏览器堆栈顶部的条目,history.go(0) 转到顶部条目。 return false 阻止浏览器在 return 上对 link 起作用。

我不知道history.replaceState()的第一个参数应该是什么。它被标识为 "state object"(参见 https://developer.mozilla.org/en-US/docs/Web/API/History_API,其中给出了示例)。我正在传递一个空对象,它似乎有效。第二个参数被标识为 "title",文档说它可以安全地为空字符串。

很高兴收到任何发现此方法缺陷或可以提出改进建议的人的来信。看起来效果不错。