How to get the previous URL in JavaScript?

后端 未结 7 905
野趣味
野趣味 2020-11-22 06:05

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

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

7条回答
  •  深忆病人
    2020-11-22 06:13

    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).

提交回复
热议问题