谷歌Chrome插件:如何从URL获取域名(tab.url)

Oto*_*Oto 15 javascript google-chrome google-chrome-extension

使用Google Chrome API的tab.url价值,从整个价值中获取域名的最佳方法是什么?

在JavaScript中,我会使用window.location.protocol&window.location.hostname.例如这样的事情:

var domain = window.location.protocol + "//" + window.location.hostname;
Run Code Online (Sandbox Code Playgroud)

但是这会获得扩展域而不是选项卡,因此无法使用该方法.所以使用类似于下面的函数...我将如何从tab.url值中删除域?

function show_alert() {
    chrome.tabs.getSelected(null, function(tab) {
        var currentURL = tab.url;
        alert(currentURL);
    });
}
Run Code Online (Sandbox Code Playgroud)

Ros*_*ski 36

由于最初回答了这个问题,因此出现了更好的解决方案.

大多数现代浏览器都支持使用的URL构造函数,它提供了访问href,hostname,path和分裂的URL的所有标准方法.

要获取域,您可以执行以下操作:

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'
})
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案.对疯狂的正则表达式说不!:-) (6认同)

Eli*_*rey 17

首先,域不包含协议.我为你的问题创建了一个正则表达式.要获取URI的主机名(您希望这样做,因为IP地址不是域),请使用以下命令:

var domain = uri.match(/^[\w-]+:\/{2,}\[?([\w\.:-]+)\]?(?::[0-9]*)?/)[1];
// Given uri = "http://www.google.com/", domain == "www.google.com"
Run Code Online (Sandbox Code Playgroud)

如果您想要原点(协议+主机(不是主机名,有区别)+可选端口)而不是域,请使用以下命令:

var origin = uri.match(/^[\w-]+:\/{2,}\[?[\w\.:-]+\]?(?::[0-9]*)?/)[0];
// Given uri = "http://www.google.com/", origin == "http://www.google.com"
Run Code Online (Sandbox Code Playgroud)

  • 太棒了 (2认同)