目前,我在一个页面上有一个“回传”链接,该链接目前在onClick处理程序中使用router.back()返回到上一页,如果当前页面导航到我的站点内,该链接通常有效,但是如果该页面被直接导航到(例如,通过书签或粘贴的URL),那么我希望“回传”链接执行一个router.push('/'),而不是返回到我的主页。我不知道如何确定之前的浏览器历史URL是否在我的站点之外来执行router.push()而不是router.back()。有人有什么建议吗?
发布于 2022-11-21 14:02:41
可以使用window?.history?.state?.idx
检查表示最新访问页面的状态的索引。
如果是window?.history?.state?.idx > 0
,这意味着用户已经在网站上导航,您可以“安全地”使用router.back(.)。如果url直接粘贴在浏览器中,则此值将等于0。
发布于 2022-06-05 21:59:44
您可以签出document.referrer
并检查URL的主机名是否与您的主机名匹配。如果是这样的话,您可以安全地使用router.back()。如果没有,您可以使用router.push('/')
。
发布于 2022-07-19 11:34:40
不幸的是,document.referrer
没有正确地处理Next。首选的方法是使用会话存储来使用useEffect钩子在_app.js中保存以前的和当前的路径。
...
const storePathValues = () => {
const storage = globalThis?.sessionStorage;
if (!storage) return;
// Set the previous path as the value of the current path.
const prevPath = storage.getItem("currentPath");
storage.setItem("prevPath", prevPath);
// Set the current path value by looking at the browser's location object.
storage.setItem("currentPath", globalThis.location.pathname);
}
useEffect(() => storePathValues, [router.asPath]);
...
这样,您就可以评估用户从哪个页面来,然后使用router.back()或router.push()。
https://stackoverflow.com/questions/72511360
复制相似问题