如何从Chrome扩展访问主机

如何从Chrome扩展访问主机

问题描述:

我正在寻找一种方法来读取当前选项卡的主机(not just hostname)。如何从Chrome扩展访问主机

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

我可以从window.location对象获得主机,但是我找不到从扩展中访问数据的方法。

给定一个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).

+0

无赖,它不是一个跨浏览器的功能,因为它不是在IE浏览器和一些移动浏览器稳定的,但它提供我当前的目的。谢谢。 – Pasaribu

+1