1

I'm encountering a very strange problem whereby the state information within a Chrome extension background.js page is not persisting Chrome sessions for a specific user. By Chrome sessions I mean closing and reopening Chrome.

All I am storing in the background.js is an array of key value pairs, that I am updating and reading as follows.

//background.js

var settings = [];
function (request, sender, sendResponse) {
    //SAVE
    if (request.cmd == "save") {
        settings[request.data.key] = request.data.value;
    }
    //RETRIEVE
    if (request.cmd == "load") {
        var myVal = settings[request.data.key];
        sendResponse(myVal);
    }
}

I did notice a setting within Chrome (advanced settings), which I can confirm is invoked for this particular user.

Continue running background apps when Google Chrome has closed.

What else could cause the background.js to lose state information between Chrome sessions?

QFDev
  • 8,668
  • 14
  • 58
  • 85

1 Answers1

4

Your settings object exists only in memory as long as background.js is loaded.

If Chrome completely shuts down, the data is lost, as it's not written in any permanent store.

"Continue running background apps when Google Chrome has closed" keeps Chrome running in the background if all Chrome visible windows are closed; but you should not rely on that for persistence. For instance, if the user logs out or reboots the machine, data will be lost.

You have many options for saving your data in a persistent way. The recommended one would be chrome.storage API, partly because your content scripts (that presumably call those commands) can access that directly.

But if you're aiming for minimal changes, you can use good old localStorage. It will only be available to your background script, since it depends on the page origin.

Here's a comparison between the two.

Community
  • 1
  • 1
Xan
  • 74,770
  • 16
  • 179
  • 206
  • Maybe I need to rethink the storage mechanism. Although on my machine the settings can persist Chrome and OS restarts and the same is true for most other users. I was always under the impression that background.js is persistent? – QFDev Jan 20 '15 at 15:09
  • That's puzzling, because no, it is not. Chrome does not "hibernate" your background page between restarts, it treats it as any other tab - except invisible. You need to rely on one of the storage APIs for persistent data. – Xan Jan 20 '15 at 15:10
  • Thanks, I will have a look at using a more reliable alternative. – QFDev Jan 20 '15 at 15:12
  • 1
    In any case, if my guess is right and you're using messaging from content scripts / options page to request settings from the background - `chrome.storage` can do a much better job. – Xan Jan 20 '15 at 15:13