javascript 如何使用 document.referrer 获取 url 的一部分?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15283013/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 00:11:30  来源:igfitidea点击:

How to get the parts of a url using document.referrer?

javascript

提问by FairyQueen

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

我需要使用document.referrer来获取以前的 URL 我还需要能够获取 URL 的部分,例如:

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?

但我不知道如何使用document.referrer. 有人有任何想法吗?

回答by kennebec

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

您可以创建一个以引用为 URL 的元素。

a elements (with hrefs) can act like location objects

a 元素(带有 hrefs)可以充当位置对象

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

回答by Aaron Powell

There's no equivalent to window.locationwith regards to document.referrerso 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:

有没有相当于window.location与问候document.referrer所以你唯一的选择将是打破字符串本身。您可以编写一个正则表达式来做到这一点,也可以依靠一系列字符串拆分:

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

回答by rodneyrehm

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

如果您想要方便并且负担得起重量,请查看URI.js或建议的URL 解析器之一。如果您不需要任何花哨<a>东西,s href 分解就可以很好地完成工作。