Javascript 是否可以使用javascript获取从浏览器访问的上一页的URL
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12005620/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to get URL of previous page visited from browser using javascript
提问by Pradip Prajapati
I am on page A.
我在 A 页。
Now I click in page A and redirected to page B. Now I click in page B and redirected to page A.
现在我点击页面 A 并重定向到页面 B。现在我点击页面 B 并重定向到页面 A。
Here i want to know the url of page B.
在这里我想知道页面 B 的 url。
I have tried document.referrer but its not working.
我试过 document.referrer 但它不起作用。
回答by Lex Eichner
document.referrer works when a user clicks on a link to navigate to the current page but I don't think it works when you do a manual redirect in a Javascript function.
当用户单击链接导航到当前页面时 document.referrer 起作用,但我认为当您在 Javascript 函数中进行手动重定向时它不起作用。
The only way I can think of is to store the URL of the page before the user is redirected to your current page.
我能想到的唯一方法是在用户重定向到您的当前页面之前存储页面的 URL。
You could store it in a hidden form or a cookie.
您可以将其存储在隐藏形式或 cookie 中。
This question has also been asked before and its worth having a quick read through here. How do you get the previous url in Javascript?
之前也有人问过这个问题,值得在这里快速阅读。你如何在Javascript中获得以前的网址?
I took this cookie example from it to show you what I mean.
我从中取出了这个 cookie 示例来向您展示我的意思。
$.cookie("previousUrl", window.location.href, {path:"/"});
回答by Willem Mulder
You can't knowthe URL of the previous page, but you can link to it using
您无法知道上一页的 URL,但可以使用以下链接链接到它
window.history.back();
or
或者
window.history.go(-1);
if you want to know ifthere is a previous page, check
如果您想知道是否有上一页,请检查
window.history.length;
If it's more than 0, there is a prev page. See https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history
如果大于 0,则有一个 prev 页面。请参阅https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history