Javascript 如何使用 chrome.tabs.getCurrent 在 Chrome 扩展中获取页面对象?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6718256/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:55:17  来源:igfitidea点击:

How do you use chrome.tabs.getCurrent to get the page object in a Chrome extension?

javascripthtmlgoogle-chrome-extensiongoogle-chrome-devtools

提问by Tom

The code is meant to output the current tab object for the page the user is viewing to the console but it just outputs undefined. It's run from within a browser action page.

该代码旨在将用户正在查看的页面的当前选项卡对象输出到控制台,但它只是输出未定义。它从浏览器操作页面中运行。

chrome.tabs.getCurrent( function(tab){
    console.log(tab);
} );

I've looked at the documentationand as far as I can tell the code seems to match what it says.

我查看了文档,据我所知,代码似乎与它所说的相符。

采纳答案by serg

Try:

尝试:

chrome.tabs.getSelected(null, function(tab){
    console.log(tab);
});

回答by Konstantin Smolyanin

The method getSelected()has been deprecated since Google Chrome 16 (but many articles in the official documentation had not yet been updated). Official message is here. To get the tab that is selected in the specified window, use chrome.tabs.query()with the argument {'active': true}. So now it should look like this:

该方法getSelected()自 Google Chrome 16 起已被弃用(但官方文档中的许多文章尚未更新)。官方消息在这里。要获取在指定窗口中选择的选项卡,请使用chrome.tabs.query()参数{'active': true}。所以现在它应该是这样的:

chrome.tabs.query({ currentWindow: true, active: true }, function (tabs) {
  console.log(tabs[0]);
});

回答by Jk L.

May be undefined if called from a non-tab context (for example, a background page or popup view).

如果从非选项卡上下文(例如,背景页面或弹出视图)调用,则可能未定义。

It looks like you should use this code not in bg.jsbut rather in cs.js.

看起来您不应该使用此代码,bg.js而应该使用cs.js.