【发布时间】:2016-07-06 20:12:14
【问题描述】:
我正在寻找一种方法来读取当前选项卡的主机 (not just hostname)。
我可以阅读网址,但似乎找不到可靠的正则表达式来提取主机。
我可以从 window.location 对象获取主机,但我找不到从扩展程序访问该数据的方法。
【问题讨论】:
标签: google-chrome google-chrome-extension
我正在寻找一种方法来读取当前选项卡的主机 (not just hostname)。
我可以阅读网址,但似乎找不到可靠的正则表达式来提取主机。
我可以从 window.location 对象获取主机,但我找不到从扩展程序访问该数据的方法。
【问题讨论】:
标签: google-chrome google-chrome-extension
给定一个 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).
【讨论】:
<a> 元素)实现相同的效果。 var a = document.createElement('a'); a.href = url; console.log(a.host);