有没有办法在JavaScript中获得之前的URL ?就像这样:

alert("previous url is: " + window.history.previous.href);

有类似的东西吗?还是我应该把它放在饼干里?我只需要知道,所以我可以做过渡从以前的URL到当前的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
    }
}

其他回答

如果有人来自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("/")
  }

如果你想在不知道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参数或服务器端会话信息可能不那么脆弱,而且肯定更有用。

文档。referrer与实际URL在所有情况下都不相同。

我有一个应用程序,我需要建立一个2帧的框架集。一个框架是已知的,另一个是我要链接的页面。看来那份文件。Referrer是理想的,因为您不必将实际的文件名传递给框架集文档。

但是,如果您稍后更改了底部框架页面,然后使用history.back(),它不会将原始页面加载到底部框架中,而是重新加载文档。引用,结果框架集消失了,你回到原来的开始窗口。

我花了点时间才明白。在历史数组中,document。referrer不仅仅是一个URL,它显然也是一个引用窗口规范。至少,这是我目前能理解的最好的方式。

我在一个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
}, []);