有没有办法在JavaScript中获得之前的URL ?就像这样:
alert("previous url is: " + window.history.previous.href);
有类似的东西吗?还是我应该把它放在饼干里?我只需要知道,所以我可以做过渡从以前的URL到当前的URL没有锚和所有的。
有没有办法在JavaScript中获得之前的URL ?就像这样:
alert("previous url is: " + window.history.previous.href);
有类似的东西吗?还是我应该把它放在饼干里?我只需要知道,所以我可以做过渡从以前的URL到当前的URL没有锚和所有的。
当前回答
如果你正在编写一个web应用程序或单页应用程序(SPA),其中路由发生在应用程序/浏览器中,而不是到服务器的往返,你可以执行以下操作:
window.history.pushState({ prevUrl: window.location.href }, null, "/new/path/in/your/app")
然后,在您的新路由中,您可以执行以下操作来检索之前的URL:
window.history.state.prevUrl // your previous url
其他回答
如果你正在编写一个web应用程序或单页应用程序(SPA),其中路由发生在应用程序/浏览器中,而不是到服务器的往返,你可以执行以下操作:
window.history.pushState({ prevUrl: window.location.href }, null, "/new/path/in/your/app")
然后,在您的新路由中,您可以执行以下操作来检索之前的URL:
window.history.state.prevUrl // your previous url
那些使用Node.js和Express的人可以设置一个会话cookie,它会记住当前页面的URL,从而允许您在下一个页面加载时检查引用者。下面是一个使用express-session中间件的例子:
//Add me after the express-session middleware
app.use((req, res, next) => {
req.session.referrer = req.protocol + '://' + req.get('host') + req.originalUrl;
next();
});
然后你可以像这样检查referrer cookie的存在:
if ( req.session.referrer ) console.log(req.session.referrer);
不要假设这个方法总是存在一个引用cookie,因为在前一个URL是另一个网站、会话被清理或刚刚创建(第一次网站加载)的情况下,它将不可用。
如果有人来自react世界,我最终使用history-library, useEffect和localStorage的组合解决了我的用例
当用户选择新项目时:
function selectProject(customer_id: string, project_id: string){
const projectUrl = `/customer/${customer_id}/project/${project_id}`
localStorage.setItem("selected-project", projectUrl)
history.push(projectUrl)
}
当用户从另一个网站回来。如果localStorage里有东西,就把他送过去。
useEffect(() => {
const projectUrl = localStorage.getItem("selected-project")
if (projectUrl) {
history.push(projectUrl)
}
}, [history])
当用户退出项目时,清空localStorage
const selectProject = () => {
localStorage.removeItem("selected-project")
history.push("/")
}
即使是文件也能解决问题。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
}
}
如果你想在不知道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的浏览器上操作历史堆栈的内容
要了解更多信息,请参阅医生