问题
I'm trying to create a simple plugin for Google Chrome. One of the functions would be a return to the last used tab, but I don't know how to do it.
So, is there any way to get the last used tab?
回答1:
You could try adding a hook into the onSelected event of the tabs and just saving that variable... soemthing like this:
var curTabID = 0;
var curWinID = 0;
chrome.tabs.onSelectionChanged.addListener(function(tabId, selectInfo) {
curTabID = tabId;
curWinID = selectInfo.windowId;
});
Then you have the window id and the tab id at all times.
回答2:
Note: This answer does not help the questioner, but I thought it may be helpful for upcoming Firefox developers, which land here, because of Firefox now sharing the same api as chrome.
Firefox webextension programmers don't have to track the tab their self. They can query it like this instead, due to the lastAccessed property:
chrome.tabs.query({
active: false
}, (tabs) => {
let tab = tabs.reduce((previous, current) => {
return previous.lastAccessed > current.lastAccessed ? previous : current;
});
// previous tab
console.log(tab);
});
Edit: It's worth to mention, that the lastAcessed timestamp is also set if a new tab is created in the background. So this method is not perfectly bullet proof, since the tab opened in the background will be treated as the last visited tab.
回答3:
I think you should use chrome.windows.getCurrent function to get the current window and chrome.tabs.query function to get the active tab in this window.
Here is an example (script from the background page):
chrome.windows.getCurrent(
function(win) {
// win is a Window object referencing the current window
chrome.tabs.query({'windowId': win.id, 'active': true},
function(tabArray) {
// tabArray is a Tab Array referencing active tab(s)
}
);
}
);
来源:https://stackoverflow.com/questions/8688887/chrome-extension-get-last-used-tab