如何从chrome扩展程序访问主机(How to access host from chrome extension)

我正在寻找一种方法来读取当前选项卡的主机( 而不仅仅是主机名 )。

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

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

I'm looking for a way to read the current tab's host (not just hostname).

I can read the url, but can't seem to find a reliable regex to extract out the host.

I can get the host from the window.location object, but I can't find a way to access that data from the extension.

最满意答案

给定URL,您可以使用URL构造函数来解析它并提取解析的URL组件 。 例如:

// 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). 
  
 

Given an URL, you can use the URL constructor to parse it and extract the parsed URL components. For instance:

// 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). 
  
 

更多推荐