如何从chrome扩展程序访问主机

时间:2016-03-20 09:25:04

标签: google-chrome google-chrome-extension

我正在寻找一种方法来阅读当前标签的主持人(not just hostname)。

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

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

1 个答案:

答案 0 :(得分:4)

根据网址,您可以使用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).