簡體   English   中英

如何使用document.referrer獲取網址的各個部分?

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

我需要使用document.referrer來獲取以前的URL我還需要能夠獲取URL的部分,如:

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

但我無法弄清楚如何使用document.referrer 有人有任何想法嗎?

您可以使用referrer作為其url創建一個元素。

元素(帶有hrefs)可以像位置對象一樣工作

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

對於document.referrer ,沒有與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('/');

如果您想要方便並且能夠負擔得起,請查看URI.js或建議的URL解析器之一 如果你不需要任何花哨的東西,那么<a> s href分解就可以了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM