0

I am working on a Chrome Extension and I need it to maintain its state each time it is opened.

For example, I have an input element that needs to stay filled-in after I close and re-open the extension.

On this page, I found an example of the manifest. It lead me to add the following to my manifest, but it didn't work:

"background": {
 "persistent": true,
"page": "popup.html"
}

Is there a way to maintain the extensions state between openings?

Lee Loftiss
  • 3,035
  • 7
  • 45
  • 73

1 Answers1

0

First things first, read the Architecture Overview of Chrome extensions.

A popup page is a "throwaway" page that only exists as long as the popup is open; you cannot influence that. As soon as the popup loses focus, its HTML document will be destroyed.

In contrast, a background "page" (which usually has no HTML markup, hence the typical use of "scripts" instead of "page") with "persistent": true exists as long as Chrome runs. As such, it can hold state information. But it's an invisible page.

The right approach would be to make the popup page dynamic, save its state to background and/or various storage APIs, and restore state when opening.

Minimal example:

// popup.js
// Suppose #myInput is a text input
document.addEventListener('DOMContentLoaded', function() {
  chrome.storage.local.get({setting: "default value"}, function(data) {
    var inputElement = document.getElementById("myInput");
    inputElement.value = data.setting;
    inputElement.addEventListener("input", function(e) {
      chrome.storage.local.set({setting: e.target.value});
    });
  });
});
Xan
  • 74,770
  • 16
  • 179
  • 206
  • Thanks for the link and info. That link was especially helpful. – Lee Loftiss Oct 16 '14 at 08:33
  • @LeeLoftiss Fun fact, I feel like I have to give that link in half of the questions I answer. This must be a more prominent part of documentation, as this is basically required reading for understanding how everything works. – Xan Oct 16 '14 at 08:34
  • I agree. All the reading I did about extensions, and I never noticed that page before. In your solution, you used the chrome storage. Would you suggest using the HTML5 local storage as well? I ask mainly because I would like to make an extension for Firefox later on and it seems this would miminize the porting I have to do later. – Lee Loftiss Oct 16 '14 at 08:37
  • 1
    Read [another answer](http://stackoverflow.com/questions/24279495/window-localstorage-vs-chrome-storage-local/24281357#24281357) I gave on the topic. In a nutshell, you can use `localStorage` in extension pages, but not in content scripts. – Xan Oct 16 '14 at 08:41
  • I see. Thanks. I think for my needs then, the HTML5 localStorage will work. – Lee Loftiss Oct 16 '14 at 08:43