Save last session of chrome extension

雨燕双飞 提交于 2019-12-13 08:07:18

问题


In my html file I have a simple table and a couple of buttons that allow adding/removing rows. If I store that html in popup.html, then every time I close chrome extension the session disappears. That is if I added some rows and put some values to the cells of that table, once I go from my extension, these rows and values disappear when I click on the extension again.

As a solution I saw putting that html to background.html and retrieving that code from popup.js:

// listeners to save/restore document.body 
window.addEventListener("unload", function(event) { 
  chrome.extension.getBackgroundPage().docBody = document.body; 
}); 

window.addEventListener("load", function(event) { 
  var 
    docBody = document.body, 
    lastDocBody = bgPage.docBody; 
  if (lastDocBody) 

docBody.parentElement.replaceChild(document.importNode(lastDocBody,true), 
docBody); 
}); 

However, it doesn't output any content of background.html to my extension.

The question is general: I would like to save the last state of my table, no matter if I closed the extension or not. How can I do this?

Or in particular, how can I load/save page from/to background.html and upload its content to popup.js


回答1:


You will have to use one of the storage APIs provided.

Best one to use is chrome.storage, but you can also use localStorage inside chrome extension pages. See this question for a comparison. You don't need background page for either.

Do note: you cannot store DOM nodes directly in such storage, since the data has to be JSON-serializable, and DOM nodes contain circular references.

So you'll need to store data used to add your rows instead of the rows themselves, and add them again when restoring state. It is a good idea anyway to store "raw" data.



来源:https://stackoverflow.com/questions/29631815/save-last-session-of-chrome-extension

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