【问题标题】:How to access host from chrome extension如何从 chrome 扩展访问主机
【发布时间】:2016-07-06 20:12:14
【问题描述】:

我正在寻找一种方法来读取当前选项卡的主机 (not just hostname)。

我可以阅读网址,但似乎找不到可靠的正则表达式来提取主机。

我可以从 window.location 对象获取主机,但我找不到从扩展程序访问该数据的方法。

【问题讨论】:

    标签: google-chrome google-chrome-extension


    【解决方案1】:

    给定一个 URL,您可以使用 URL constructor 对其进行解析并提取 parsed URL components。例如:

    // Just an example, there are many ways to get a URL in an extension...
    var url = 'http://example.com:1234/test?foo=bar#hello=world';
    var parsedUrl = new URL(url);
    console.log(parsedUrl.host);
    
    // Or if you want a one-liner:
    console.log(new URL(url).host);
    Open the JavaScript console, and you'll see "example.com:1234" (2x).

    【讨论】:

    • 遗憾的是,它不是跨浏览器功能,因为它在 IE 和一些移动浏览器中不稳定,但它符合我当前的目的。谢谢。
    • @Pasaribu 如果 URL 是绝对的(即完整的 URL),您可以使用锚点(<a> 元素)实现相同的效果。 var a = document.createElement('a'); a.href = url; console.log(a.host);
    猜你喜欢
    • 2017-10-22
    • 2013-12-08
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多