How long are background scripts valid for?

I am looking to add a feature to my web extension that will give the user a notification after x amount of times using my add-on, asking for them to rate my add-on. When the user clicks the button and is directed to the extension’s AMO page, I want the notification to be forever hidden.

I will obviously need to use my background.js file to implement this. I was just curious how long the background.js file will keep variables active for before they are reset? I’ll be storing a variable in the background.js file that will keep track of how many times the user has used the add-on, so obviously I don’t want this variable to reset every time that the user restarts Firefox.

On a side note, can anyone think of a better way to go about implementing the feature that I have described?

You can’t “store variables in a *.js file”. That’s not how things work at all.

When Firefox (and thus your extension) starts, it creates an JavaScript execution context, and execute the code from your .js files in it. That code can create variables, which are linked to that context; they have no further connection to the .js file they originate from. The variables are lost when your background context unloads, that is: when Firefox shuts down, when your extension reloads (e.g. due to an update) or is disabled or when (currently only in Chrome) the extensions background page gets suspended (to save resources).

The next time your extension starts, it will load the same .js files and create the same variables with the same values as before. So you definetly have a “reset” every time the extension or the browser starts.

To do what you suggeted, you need some kind of persistent storage.

  • chome.storage.local: The most persistent you will ever get in a browser. I think there isn’t event a UI to reset this. But you need to add the “storage” permission. On the other hand you will need this as soon as you want to save any user preferences anyway.
  • Any other kind of web storage (cookies, local storage, indexedDB, …): You won’t need to declare permissions (I think), but your storage may be reset if the user resets for example the cookies.
3 Likes

Thanks for that information. I’m going to use the storage option then.