-1

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

Sergey Ivanov
  • 3,719
  • 7
  • 34
  • 59
  • possible duplicate of [how not to lose data when closing and opening chrome extension popup](http://stackoverflow.com/questions/29335806/how-not-to-lose-data-when-closing-and-opening-chrome-extension-popup) – Xan Apr 14 '15 at 16:15

1 Answers1

0

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.

Community
  • 1
  • 1
Xan
  • 74,770
  • 16
  • 179
  • 206
  • Yes, I saw these questions, but it doesn't show how can I solve my problem. In particular, I'm interested in how I can load/save from/to background.html page. Or otherwise provide how can I store my table in chrome.storage. – Sergey Ivanov Apr 14 '15 at 17:16
  • My answer basically answers that. You need to store data that, if put into your row-adding functions, will produce your table. How to read/write that storage is covered elsewhere, including the documentation I linked. – Xan Apr 14 '15 at 17:18
  • You _do_ understand that without seeing code that you use to generate the table, a more detailed answer is impossible? I said twice already that directly storing DOM nodes is not an option. – Xan Apr 15 '15 at 08:00