Chrome 分机:Javascript 询问主机名的 URL 字符串
Chrome Ext: Javascript interrogate URL string for hostname
Note. This is not interrogate the url that you get from window.location
我正在使用 chrome.webRequest.onBeforeRequest.addListener
其中 return 的详细信息。这些详细信息是:
{
frameId: 0,
method: "GET",
parentFrameId: -1,
requestId: "687379",
tabId: 1721765993,
timeStamp: 1543573944865.511,
type: "main_frame",
url: "https://whosebug.com"
}
这意味着我只能通过使用 details.url
获得它 URL,它是 return 中的一个字符串。在这个例子中是:
url: "https://whosebug.com"
我只想获取主机名:
whosebug.com
有https或者http的时候就会出现问题。如果有子域或有额外路径。
如何只获取主机名?
这是我使用的一个巧妙的小技巧:
function processUrl(url) {
var a = document.createElement('a');
a.href = url;
return a.hostname;
}
然后将您的 details.url
传递给该函数。
这会创建一个元素,浏览器引擎会处理 a 元素并计算出您的主机名等。因此您可以 return a.hostname
。
编辑
如下所述,这可能有点过时了。另一个很好的解决方案是:
function processUrl(url) {
return new URL(url).hostname
}
Note. This is not interrogate the url that you get from
window.location
我正在使用 chrome.webRequest.onBeforeRequest.addListener
其中 return 的详细信息。这些详细信息是:
{
frameId: 0,
method: "GET",
parentFrameId: -1,
requestId: "687379",
tabId: 1721765993,
timeStamp: 1543573944865.511,
type: "main_frame",
url: "https://whosebug.com"
}
这意味着我只能通过使用 details.url
获得它 URL,它是 return 中的一个字符串。在这个例子中是:
url: "https://whosebug.com"
我只想获取主机名:
whosebug.com
有https或者http的时候就会出现问题。如果有子域或有额外路径。
如何只获取主机名?
这是我使用的一个巧妙的小技巧:
function processUrl(url) {
var a = document.createElement('a');
a.href = url;
return a.hostname;
}
然后将您的 details.url
传递给该函数。
这会创建一个元素,浏览器引擎会处理 a 元素并计算出您的主机名等。因此您可以 return a.hostname
。
编辑
如下所述,这可能有点过时了。另一个很好的解决方案是:
function processUrl(url) {
return new URL(url).hostname
}