使用Google Chrome API的tab.url value,从整个值中获取域名的最佳方法是什么?
在JavaScript中,我会使用window.location.protocol & window.location.hostname。例如,如下所示:
var domain = window.location.protocol + "//" + window.location.hostname;但是它得到的是扩展域,而不是标签,所以不能使用该方法。因此,使用类似于下面的函数...如何从tab.url值中仅剥离域名?
function show_alert() {
chrome.tabs.getSelected(null, function(tab) {
var currentURL = tab.url;
alert(currentURL);
});
}发布于 2016-05-27 23:09:59
由于这个问题最初得到了回答,因此出现了一个更好的解决方案。
大多数现代浏览器现在都支持URL constructor的使用,它提供了对href、hostname、path和所有标准的网址拆分方式的访问。
要获取域,您可以执行以下操作:
chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
var tab = tabs[0];
var url = new URL(tab.url)
var domain = url.hostname
// `domain` now has a value like 'example.com'
})发布于 2010-09-11 09:54:33
首先,域不包括协议。我已经为你的问题创建了一个正则表达式。要获取URI的主机名(您可能希望这样做,因为IP地址不是域),请使用以下命令:
var domain = uri.match(/^[\w-]+:\/{2,}\[?([\w\.:-]+)\]?(?::[0-9]*)?/)[1];
// Given uri = "http://www.google.com/", domain == "www.google.com"如果您想要源(协议+主机(不是主机名,有区别)+可选端口)而不是域,请使用the following
var origin = uri.match(/^[\w-]+:\/{2,}\[?[\w\.:-]+\]?(?::[0-9]*)?/)[0];
// Given uri = "http://www.google.com/", origin == "http://www.google.com"发布于 2019-01-04 05:10:51
chrome.tabs.query(
{
active: true,
currentWindow: true
},
([currentTab]) => {
const url = new URL(currentTab.url);
const domain = url.hostname;
console.log(domain);
}
);组合:https://stackoverflow.com/a/37486863/8023318,但不使用折旧的getSelected和https://stackoverflow.com/a/48755190/8023318。我想看看这是否可以通过getCurrent完成。
https://stackoverflow.com/questions/3689423
复制相似问题