2016-03-20 139 views
2

我正在尋找一種方法來讀取當前選項卡的主機(not just hostname)。如何從Chrome擴展訪問主機

我可以讀取網址,但似乎無法找到一個可靠的正則表達式來提取出主機。

我可以從window.location對象獲得主機,但是我找不到從擴展中訪問數據的方法。

回答

4

給定一個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