gpt4 book ai didi

javascript - 谷歌浏览器插件 : How to get domain from URL (tab. 网址)

转载 作者:可可西里 更新时间:2023-11-01 01:26:52 26 4
gpt4 key购买 nike

使用 Google Chrome API 的 tab.url value ,从整个值中获取域的最佳方法是什么?

在 JavaScript 中,我会使用 window.location.protocolwindow.location.hostname。例如这样的事情:

var domain = window.location.protocol + "//" + window.location.hostname;

但是那获取的是扩展域而不是选项卡,所以不能使用该方法。因此,使用类似于下面的函数...我如何从 tab.url 值中删除域?

function show_alert() {
chrome.tabs.getSelected(null, function(tab) {
var currentURL = tab.url;
alert(currentURL);
});
}

最佳答案

由于最初回答了这个问题,所以出现了更好的解决方案。

大多数现代浏览器现在都支持使用 URL constructor ,它提供对 hrefhostnamepath 和所有拆分 URL 的标准方法的访问。

要获取域,您可以执行以下操作:

chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
var tab = tabs[0];
var url = new URL(tab.url)
var domain = url.hostname
// `domain` now has a value like 'example.com'
})

关于javascript - 谷歌浏览器插件 : How to get domain from URL (tab. 网址),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3689423/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com