Google chrome 如何获取chrome扩展的当前选项卡URL?

Google chrome 如何获取chrome扩展的当前选项卡URL?,google-chrome,google-chrome-extension,Google Chrome,Google Chrome Extension,我知道有很多类似的问题,但我似乎无法让它工作 我正在尝试从我的Chrome扩展中获取当前选项卡的URL。无论如何,警报(tab.url)返回“未定义”。我已将“选项卡”添加到manifest.json中的权限中。有什么想法吗 <html> <head> <script> chrome.tabs.getSelected(null, function(tab) { tab = tab.id; tabUrl = tab.ur

我知道有很多类似的问题,但我似乎无法让它工作

我正在尝试从我的Chrome扩展中获取当前选项卡的URL。无论如何,警报(tab.url)返回“未定义”。我已将“选项卡”添加到manifest.json中的权限中。有什么想法吗

<html>
<head>
<script>

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

        alert(tab.url);
    });

</script>
</head>

chrome.tabs.getSelected(空,函数(选项卡){
tab=tab.id;
tabUrl=tab.url;
警报(tab.url);
});

问题出在这一行:

tab = tab.id;
应该是这样的:

var tabId = tab.id;

仅供谷歌用户参考:

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

  });

这就是我的工作原理:

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);
});
在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);
});

在ES6的帮助下,您可以轻松编写更好的代码:)

如果有人像我一样使用,为跨浏览器的支持

//使用异步函数
const[currentTab]=等待browser.tabs.query({
主动:对,
currentWindow:对,
});
log({id:currentTab.id,url:currentTab.url});

您错误地更改了变量选项卡。。。下次小心:)getSelected已弃用。请使用tabs.query{active:true}嗨,我需要焦点选项卡信息。。如果我在浏览器中有5个以上的选项卡,如果单击(聚焦)选项卡1,然后单击“动作触发器”或选项卡2/3/4/5。。每次选项卡聚焦时,它都应该触发。那么我能做什么呢?此方法已被弃用。是否有任何方法可以避免查询/轮询,而是通过聆听单击来确定活动选项卡?现在应选择此方法,因为旧方法由于多种原因无法工作。
chrome.tabs.query({
  active: true,
  currentWindow: true
}, ([currentTab]) => {
  console.log(currentTab.id);
});