Reputation: 71
I'm trying to write a chrome extension that needs to keep a state of each tabs in which the script will be executed. My first idea was to have a map in the background page that associate the current tab id to the state of the tab.
I've just seen that the chome.tabs.getCurrent
method cannot be used to get the tab id of page that execute the content script.
I've seen that the chrome.tabs.getSelected
method is often recommended but I can't use this method because my script can be called in background (for example, when a page is reloaded automaticly) and then the tab can be not selected.
So I whould know how to get the id of the current tab or how to keep a state of a tab.
Upvotes: 3
Views: 2265
Reputation: 71
In fact, I only need to access to sender.tab.id
Script in the backgroung page :
var states = new Object();
chrome.extension.onRequest.addListener(
function(request, sender, sendResponse) {
if(request.method == "setState") {
states[sender.tab.id] = request.state;
sendResponse({});
} else if(request.method == "getState") {
var state = states[sender.tab.id];
sendResponse(state);
} else {
sendResponse({}); // snub them.
}
});
And the code I need in the content script :
function saveState(state) {
chrome.extension.sendRequest({method: "setState", state: state}, function() {});
}
function restoreState() {
chrome.extension.sendRequest({method: "getState"}, doTheJob);
}
function doTheJob(state) {
// do the job
console.log(state);
var newState;
if(state==undefined || state==null) {
newState = { count: 1 };
} else {
newState = state;
newState.count++;
}
saveState(newState);
}
restoreState();
Upvotes: 3