JavaScript路径名和引荐者

8

如何在JavaScript中执行与document.location.pathname相同的功能,但使用referrer?因此类似于document.referrer.pathname?

谢谢。


尝试使用document.referrer怎么样?例如: alert(document.referrer); - MRR0GERS
3个回答

7
你可以使用以下代码从document.referrer中提取路径名并使用new URL()进行解析:
const url = new URL(document.referrer)
url.pathname

请务必为IE 10及以下版本使用URL polyfill,可以轻松地通过https://polyfill.io/v3/polyfill.js?features=URL实现。


当您点击链接时,错误信息为“/禁用缩小(从URL路径中删除'.min')以获取更多信息/”,而在删除“min”时,错误信息为“/当前设置未找到填充/”。也许您想发布其他内容? - Abandoned Cart
谢谢@AbandonedCart提醒我,我已经更改了Polyfill.io链接。 - kylewelsby
请注意,URL构造函数在未提供有效的URL时(例如未设置引用页面时的空字符串)会抛出异常。根据使用情况,提供基本URL可能是防止此问题的好方法:new URL(document.referrer, "http://example.com/") - Wilco Verhoef

6
不,你只能手动提取所需部分:
document.referrer.replace(/^[^:]+:\/\/[^/]+/, '').replace(/#.*/, '')

这并不完全正确,因为 document.location.pathname 也会剥离 URL 的参数。你需要使用: document.referrer.replace(/^[^:]+:\/\/[^/]+/, '').replace(/#.*/, '').replace(/\?.*/, '')来同时删除引荐者的参数。 - clement g

0
你可以使用document.referrer获取引用文档的URL。这是你指的吗?

不,我只想要路径,所以如果是http://www.google.com/sdfhisdfsdf,我只需要/sdfhisdfsdf这部分..哈哈 - Matt
啊啊啊...我想你得自己解析一下..或者用正则表达式来拯救? - Teja Kantamneni

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接