简体   繁体   中英

How to grab referrer from a redirect using JavaScript?

I know that I can find out the referrer using:

document.referrer;

However, I have a one page website, and a redirection set to send all other pages in that website to the home page. I would like to have a way of capturing the link that originated the redirection. In this case, document.referrer is always empty.

So I guess, I need to know:

  1. How do I set a referrer parameter before the redirection?
  2. How do I capture that parameter with JavaScript in the home page?

You could pass it along in a URL parameter. For example, Google does something similar when you click a search result; the browser actually goes to google.com/url?url=https%3A%2F%2Fthe-site-you-want.com .

So you could redirect your users to 'http://your-site.com/?referrer='+ encodeURIComponent(document.referrer) , and then once it hits the homepage, you can extract that value and run decodeURIComponent.

encodeURIComponent is a method that makes a value safe to put in a URL. decodeURIComponent is the reverse process.

Alternatively, you could put it in a hash rather than the querystring, like 'http://your-site.com/#'+ encodeURIComponent(document.referrer) . Several client-side routers use this. Although that may break the back button unless you spend more time learning about pushState. When Twitter first used twitter.com/#!/foo-bar as a URL scheme, it broke many things. But it may be useful to you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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