开发者

How to get the previous URL in JavaScript?

Is there any way to get the previous URL in JavaScript? Something like this:

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

Is there something like that? Or should I just store it in a cookie? I only need to know so I can do transitions from the previous URL to the current URL without anchors and all t开发者_运维问答hat.


document.referrer

in many cases will get you the URL of the last page the user visited, if they got to the current page by clicking a link (versus typing directly into the address bar, or I believe in some cases, by submitting a form?). Specified by DOM Level 2. More here.

window.history allows navigation, but not access to URLs in the session for security and privacy reasons. If more detailed URL history was available, then every site you visit could see all the other sites you'd been to.

If you're dealing with state moving around your own site, then it's possibly less fragile and certainly more useful to use one of the normal session management techniques: cookie data, URL params, or server side session info.


If you want to go to the previous page without knowing the url, you could use the new 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.

But you can't manipulate the content of the history stack on browser that doesn't support the HTML5 History API

For more information see the doc


If you are writing a web app or single page application (SPA) where routing takes place in the app/browser rather than a round-trip to the server, you can do the following:

window.history.pushState({ prevUrl: window.location.href }, null, "/new/path/in/your/app")

Then, in your new route, you can do the following to retrieve the previous URL:

window.history.state.prevUrl // your previous url


document.referrer is not the same as the actual URL in all situations.

I have an application where I need to establish a frameset with 2 frames. One frame is known, the other is the page I am linking from. It would seem that document.referrer would be ideal because you would not have to pass the actual file name to the frameset document.

However, if you later change the bottom frame page and then use history.back() it does not load the original page into the bottom frame, instead it reloads document.referrer and as a result the frameset is gone and you are back to the original starting window.

Took me a little while to understand this. So in the history array, document.referrer is not only a URL, it is apparently the referrer window specification as well. At least, that is the best way I can understand it at this time.


<script type="text/javascript">
    document.write(document.referrer);
</script>

document.referrer serves your purpose, but it doesn't work for Internet Explorer versions earlier than IE9.

It will work for other popular browsers, like Chrome, Mozilla, Opera, Safari etc.


If anyone is coming from React-world, I ended up solving my use-case using a combination of history-library, useEffect and localStorage

When user selects new project:

  function selectProject(customer_id: string, project_id: string){
    const projectUrl = `/customer/${customer_id}/project/${project_id}`
    localStorage.setItem("selected-project", projectUrl)
    history.push(projectUrl)
  }

When user comes back from another website. If there's something in localStorage, send him there.

  useEffect(() => {
    const projectUrl = localStorage.getItem("selected-project")
    if (projectUrl) {
      history.push(projectUrl)
    }
  }, [history])

When user has exited a project, empty localStorage

  const selectProject = () => {
    localStorage.removeItem("selected-project")
    history.push("/")
  }


I had the same issue on a SPA Single Page App, the easiest way I solved this issue was with local storage as follows:

I stored the url I needed in local storage

useEffect(() => {
const pathname = window.location.href; //this gives me current Url
localstorage.setItem('pageUrl',JSON.stringify(pathname))
}, []);

On the next screen (or few screens later) I fetched the url can replaced it as follows

useEffect(() => {
     const pathname = localstorage.getItem('pageUrl');
     return pathname ? JSON.parse(pathname) : ''
     window.location.href = pathname; //this takes prevUrl from local storage and sets it
}, []);


Those of you using Node.js and Express can set a session cookie that will remember the current page URL, thus allowing you to check the referrer on the next page load. Here's an example that uses the express-session middleware:

//Add me after the express-session middleware    
app.use((req, res, next) => {
    req.session.referrer = req.protocol + '://' + req.get('host') + req.originalUrl;
    next();
});

You can then check for the existance of a referrer cookie like so:

if ( req.session.referrer ) console.log(req.session.referrer);

Do not assume that a referrer cookie always exists with this method as it will not be available on instances where the previous URL was another website, the session was cleaned or was just created (first-time website load).


Wokaround that work even if document.referrer is empty:

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
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜