简体   繁体   English

Go 从导航历史中返回上一个 URL 并替换当前的 URL

[英]Go back to the Previous URL and replace the current URL from the Navigation History

i need to go back to the previous URL when a button is click.单击按钮时,我需要 go 回到以前的 URL。

ex: previous URL:例如:以前的 URL:

www.mysite.com 

current URL:当前 URL:

www.mysite.com/name/

user clicks the button: it goes back to:用户点击按钮:它返回到:

www.mysite.com 

but I also need to replace: www.mysite.com/name/ on the browser Navigation History.但我还需要在浏览器导航历史记录中替换: www.mysite.com/name/

how to achieve this with javascript?如何用 javascript 实现这一点?

I try using the location.replace(URL) as this removes the URL from the navigation history but what should I supply to the URL argument?我尝试使用location.replace(URL) ,因为这会从导航历史记录中删除 URL,但我应该为 URL 参数提供什么? knowing the fact that I need to go back.知道我需要 go 回来的事实。

You can use the window.history.replaceState method to replace the current URL in the browser's navigation history with a new URL. Here is an example of how you can use this method to go back to the previous URL:您可以使用 window.history.replaceState 方法将浏览器导航历史记录中当前的 URL 替换为新的 URL。以下是如何使用此方法将 go 变回之前的 URL 的示例:

function goBack() {
  var currentUrl = window.location.href;
  var previousUrl = window.history.state.previousUrl;

  window.history.replaceState({previousUrl: currentUrl}, '', previousUrl);
  window.history.back();
}

To use this function, you will need to store the previous URL in the browser's history state when the user navigates to the current URL. You can do this by calling the window.history.pushState method before navigating to the new URL:要使用这个function,当用户导航到当前的URL时,你需要在浏览器的历史state中存储之前的URL。你可以通过在导航到新的8:816688之前调用window.history.pushState方法来实现

window.history.pushState({previousUrl: currentUrl}, '', currentUrl);
window.location.href = newUrl;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM