问题
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?
回答1:
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});
});
});
});
来源:https://stackoverflow.com/questions/26398014/how-can-i-instruct-chrome-extension-to-not-reload-my-html-each-time-it-is-opened