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

主宰稳场 提交于 2019-11-29 04:54:35

问题


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 documentation and as far as I can tell the code seems to match what it says.


回答1:


Try:

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



回答2:


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:

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



回答3:


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.js but rather in cs.js.



来源:https://stackoverflow.com/questions/6718256/how-do-you-use-chrome-tabs-getcurrent-to-get-the-page-object-in-a-chrome-extensi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!