保存最后一个Chrome扩展会话 [英] Save last session of chrome extension

查看:239
本文介绍了保存最后一个Chrome扩展会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的html文件中,我有一个简单的表格和几个允许添加/删除行的按钮。如果我将这个HTML存储在popup.html中,那么每当我关闭Chrome扩展时,会话就会消失。也就是说,如果我添加了一些行并将某些值添加到该表的单元格中,则一旦从我的扩展名中去,这些行和值就会在再次单击该扩展名时消失。



作为解决方案,我将该html添加到background.html并从popup.js中检索该代码:

  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);
});

然而,它不会将background.html的任何内容输出到我的扩展中。



问题是一般的:无论我是否关闭扩展名,我都想保存表格的最后一个状态。我怎样才能做到这一点?



或者特别是,我怎样才能从/到background.html加载/保存页面,并将其内容上传到popup.js



最好使用 chrome.storage ,但您也可以使用 localStorage 内部扩展页面。有关比较,请参阅此问题。你不需要后台页面。

注意:你不能直接在这样的存储中存储DOM节点,因为数据必须是JSON序列化的,并且DOM节点包含循环引用。



因此,您需要存储用于添加行的数据,而不是行本身,并在恢复状态时再次添加它们。无论如何,存储原始数据是个好主意。


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

解决方案

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.

这篇关于保存最后一个Chrome扩展会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆