【问题标题】:Google Chrome Plugin: How to get domain from URL (tab.url)Google Chrome 插件:如何从 URL (tab.url) 获取域
【发布时间】:2010-09-11 01:22:53
【问题描述】:

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

在 JavaScript 中,我会使用 window.location.protocolwindow.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);
    });
}

【问题讨论】:

    标签: javascript google-chrome google-chrome-extension


    【解决方案1】:

    自从最初回答了这个问题以来,已经出现了更好的解决方案。

    现在大多数现代浏览器都支持使用URL constructor,它提供对hrefhostnamepath 的访问以及所有拆分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'
    })
    

    【讨论】:

    • 这应该是公认的答案。对疯狂的正则表达式说不! :-)
    • @ross-zurowski 能否请您查看我关于从已折旧的getSelected 方法迁移以及可能使用getCurrent 而不是query 的帖子? stackoverflow.com/a/54029859/8023318
    • @kinghat 感谢您的 ping。我刚刚更新了这个答案以使用新的query API,而不是旧的getSelected
    • 感谢@RossZurowski!你能让getCurrent 以任何方式工作吗?
    • @kinghat,我没试过。根据Chrome release notes,使用query({ active: true }) 是获取当前选项卡的新推荐方法——我认为是因为getCurrentbackground pages of extensions 返回undefined
    【解决方案2】:

    首先,域不包含协议。我为您的问题创建了一个正则表达式。要获取 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"
    

    【讨论】:

      【解决方案3】:
      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,但不使用已折旧的getSelectedhttps://stackoverflow.com/a/48755190/8023318。想看看这是否可以通过getCurrent 完成。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-12-04
        • 2010-10-08
        • 1970-01-01
        • 2011-07-10
        • 1970-01-01
        • 2010-09-22
        相关资源
        最近更新 更多