Reputation: 155
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?
Upvotes: 3
Views: 4498
Reputation: 4869
Chrome 121+ or 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);
});
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.
Upvotes: 3
Reputation: 7948
For V3
let lastTabID = 0
let lastWindowID = 0
chrome.tabs.onActivated.addListener(({tabId, windowId}) => {
lastTabID = tabId
lastWindowID = windowId
})
It needs an activeInfo which is an object that contains property
tabId
andwindowId
and you can use Object restructuring to help you (i.e. {tabId, windowID} = activeInfo
)
V2 to V3
Upvotes: 1
Reputation: 70513
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.
Upvotes: 7
Reputation: 1746
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)
}
);
}
);
Upvotes: 1