How can I instruct Chrome Extension to NOT reload my HTML each time it is opened?

丶灬走出姿态 提交于 2019-12-20 05:46:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!