有没有办法在JavaScript中获得之前的URL ?就像这样:
alert("previous url is: " + window.history.previous.href);
有类似的东西吗?还是我应该把它放在饼干里?我只需要知道,所以我可以做过渡从以前的URL到当前的URL没有锚和所有的。
有没有办法在JavaScript中获得之前的URL ?就像这样:
alert("previous url is: " + window.history.previous.href);
有类似的东西吗?还是我应该把它放在饼干里?我只需要知道,所以我可以做过渡从以前的URL到当前的URL没有锚和所有的。
当前回答
如果你想在不知道url的情况下跳转到上一页,你可以使用新的History api。
history.back(); //Go to the previous page
history.forward(); //Go to the next page in the stack
history.go(index); //Where index could be 1, -1, 56, etc.
但是你不能在不支持HTML5 history API的浏览器上操作历史堆栈的内容
要了解更多信息,请参阅医生
其他回答
document.referrer
在许多情况下,如果用户通过点击链接到达当前页面(而不是直接在地址栏中输入,或者我相信在某些情况下,通过提交表单?),将为您提供用户访问的最后一个页面的URL。由DOM级别2指定。更多的在这里。
窗口。history允许导航,但出于安全和隐私原因,不允许访问会话中的url。如果有更详细的URL历史记录,那么你访问的每个网站都可以看到你去过的所有其他网站。
如果您正在处理在您自己的站点上移动的状态,那么使用一种正常的会话管理技术:cookie数据、URL参数或服务器端会话信息可能不那么脆弱,而且肯定更有用。
如果你想在不知道url的情况下跳转到上一页,你可以使用新的History api。
history.back(); //Go to the previous page
history.forward(); //Go to the next page in the stack
history.go(index); //Where index could be 1, -1, 56, etc.
但是你不能在不支持HTML5 history API的浏览器上操作历史堆栈的内容
要了解更多信息,请参阅医生
我在一个SPA单页应用程序上也有同样的问题,我解决这个问题的最简单的方法是使用本地存储,如下所示:
我将需要的url存储在本地存储中
useEffect(() => {
const pathname = window.location.href; //this gives me current Url
localstorage.setItem('pageUrl',JSON.stringify(pathname))
}, []);
在接下来的屏幕(或几个屏幕后)我获取的url可以替换它如下
useEffect(() => {
const pathname = localstorage.getItem('pageUrl');
return pathname ? JSON.parse(pathname) : ''
window.location.href = pathname; //this takes prevUrl from local storage and sets it
}, []);
如果你正在编写一个web应用程序或单页应用程序(SPA),其中路由发生在应用程序/浏览器中,而不是到服务器的往返,你可以执行以下操作:
window.history.pushState({ prevUrl: window.location.href }, null, "/new/path/in/your/app")
然后,在您的新路由中,您可以执行以下操作来检索之前的URL:
window.history.state.prevUrl // your previous url
即使是文件也能解决问题。Referrer为空:
let previousUrl = null;
if(document.referrer){
previousUrl = document.referrer;
sessionStorage.setItem("isTrickApplied",false);
}else{
let isTrickApplied= sessionStorage.getItem("isTrickApplied");
if(isTrickApplied){
previousUrl = sessionStorage.getItem("prev");
sessionStorage.setItem("isTrickApplied",false);
}else{
history.back(); //Go to the previous page
sessionStorage.setItem("prev",window.location.href);
sessionStorage.setItem("isTrickApplied",true);
history.forward(); //Go to the next page in the stack
}
}