最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get the parts of a url using document.referrer? - Stack Overflow

programmeradmin2浏览0评论

I need to use document.referrer to get the previous URL I also need to be able to get the parts of the URL like:

window.location.protocol
window.location.host
window.location.pathname

but I can't figure out how to do it with document.referrer. Anyone got any ideas?

I need to use document.referrer to get the previous URL I also need to be able to get the parts of the URL like:

window.location.protocol
window.location.host
window.location.pathname

but I can't figure out how to do it with document.referrer. Anyone got any ideas?

Share Improve this question edited Mar 7, 2013 at 22:27 MikeSmithDev 15.8k4 gold badges60 silver badges91 bronze badges asked Mar 7, 2013 at 22:27 FairyQueenFairyQueen 2,3738 gold badges38 silver badges58 bronze badges 2
  • possible duplicate of Creating a new Location object in javascript – Explosion Pills Commented Mar 7, 2013 at 22:29
  • window.location is an object, with handy dandy methods for grabbing the different bits. document.referrer on the other hand is a string, and so that'll need to be parsed manually. – ultranaut Commented Mar 7, 2013 at 22:33
Add a comment  | 

3 Answers 3

Reset to default 13

You can create an a element with the referrer as its url.

a elements (with hrefs) can act like location objects

var a=document.createElement('a');
a.href=document.referrer;
alert([a.protocol,a.host,a.pathname].join('\n'));
a='';

There's no equivalent to window.location with regards to document.referrer so your only option will be to break down the string itself. You could write a regex to do that or rely on a series of string splits:

var parts = document.referrer.split('://')[1].split('/');
var protocol = document.referrer.split('://')[0];
var host = parts[0];
var pathName = parts.slice(1).join('/');

If you want the convenience and can afford the weight, have a look at URI.js or one of the suggested URL parsers. If you don't need anything fancy, <a>s href decomposition will do the job just fine.

发布评论

评论列表(0)

  1. 暂无评论