如何在Chrome扩展程序中获取当前选项卡的URL?

88

我知道stackoverflow上有许多类似的问题,但是我似乎无法让它工作。

我正在尝试从我的Chrome扩展程序中获取当前选项卡的URL。然而,alert(tab.url)返回“Undefined”。我已将“tabs”添加到manifest.json中的权限中。有任何想法吗?

<html>
<head>
<script>

    chrome.tabs.getSelected(null, function(tab) {
        tab = tab.id;
        tabUrl = tab.url;

        alert(tab.url);
    });

</script>
</head>

4
该方法已被弃用。看这里! - Reyraa
有没有办法避免查询/轮询,而是监听点击来确定活动选项卡? - Alexander Mills
9个回答

162

提醒谷歌用户一下:

OP使用的方法已被弃用。为了获取用户正在查看的选项卡,并且仅在他们正在查看的窗口中使用此方法:

chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
  // since only one tab should be active and in the current window at once
  // the return variable should only have one entry
  var activeTab = tabs[0];
  var activeTabId = activeTab.id; // or do whatever you need
});

3
现在应该选择这个,因为旧方法由于多种原因已经行不通。 - NateDSaint

34
问题出在这一行:
tab = tab.id;

应该是这样的:

var tabId = tab.id;

你不小心改变了变量tab...下次要小心哦 :) - fedmich
5
getSelected方法已弃用,请使用tabs.query {active: true}。 tabs#method-getSelected - contributorpw
嗨,我需要“聚焦标签信息”...如果浏览器中有超过5个标签,如果单击(聚焦)标签1,则会触发“操作触发器”或标签2/3/4/5..每次聚焦一个标签时都应该触发。那我该怎么办? - Mani Kasi

15

在 manifest.json 文件中:

"permissions": [
    "tabs"
]

在JavaScript中:

chrome.tabs.query({
    active: true,
    lastFocusedWindow: true
}, function(tabs) {
    // and use that tab to fill in out title and url
    var tab = tabs[0];
    console.log(tab.url);
    alert(tab.url);
});

9
这是对我有效的方法:
chrome.tabs.query({
    active: true,
    lastFocusedWindow: true
}, function(tabs) {
    // and use that tab to fill in out title and url
    var tab = tabs[0];
    console.log(tab.url);
    alert(tab.url);
});

嗨,我尝试了这个,但是没有起作用。 - Remo Bajwa

6

通过使用ES6,您可以轻松编写更好的代码 :)

chrome.tabs.query({
  active: true,
  currentWindow: true
}, ([currentTab]) => {
  console.log(currentTab.id);
});

4

最新版本表示它必须是这样的

async function getCurrentTab() {
  let queryOptions = { active: true, lastFocusedWindow: true };
  let [tab] = await chrome.tabs.query(queryOptions);
  return tab;
}

您必须在manifest.json中添加以下内容

"permissions: [
    "tabs"
]


3

记得将这段代码添加到你的manifest.json文件中

"permissions": [
    "tabs"
] 


0

对我来说,根据Kartik Kkartin的回答,我缺少了"tabs"权限

我的后台脚本中其余的代码

chrome?.tabs?.onUpdated?.addListener((tabId, changeInfo, tab) => {
  if (changeInfo.status == 'complete') {
    console.log('tabId', tabId, 'changeInfo', changeInfo, 'tab', tab)
  }
})

这将记录选项卡信息,包括加载选项卡时tab.url中的URL


0

如果有人像我一样使用Web Extension Polyfill来实现跨浏览器支持。

// using async function
const [currentTab] = await browser.tabs.query({
  active: true,
  currentWindow: true,
});

console.log({ id: currentTab.id, url: currentTab.url });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接