保存Chrome扩展程序数据(使用LocalForage)

Saving Chrome Extension Data (with LocalForage)

本文关键字:使用 LocalForage 数据 Chrome 扩展 程序 保存      更新时间:2023-09-26

我是 Web 和 chrome 扩展程序开发的新手,正在尝试使用 localForage API 来存储我的 chrome 扩展程序的数据 - 目前每次切换到新选项卡时我都会丢失所有内容,但我希望数据保留,直到用户明确清除所有内容(因此即使在多个会话等)

我决定尝试一下 localForage api(因为它应该像 localStorage 但更简单),感觉我错过了一些重要的东西 - 我可以毫无问题地设置项目/获取项目,但它实际上并没有保存任何数据。

我如何确保我的数据在切换标签页(以及多个浏览会话)时保留?

使用localForage.getItem/setItem-这似乎在使用数据方面有效,但在切换选项卡时没有做任何事情来保存它

citeUrl(values, function(citation) 
    {
      count++;
      var string = citation[0];
      localforage.setItem(string, [citation[0],citation[1]], function(err, value) 
      {// Do other things once the value has been saved.
        console.log(value[0] + " " + value[1]);
      });
      /*var result = document.getElementById('cite[]');
      result.style.visibility = 'visible'; 
      result.style.display = 'block';
      result.innerHTML = citation[0];
      renderStatus(citation[1]);*/
      for(i = 0; i < count ; i++)
      {
        var newCitation = document.createElement('div');
        localforage.getItem(citation[i], function(err, value)
          {
            newCitation.innerHTML = value[1] + "<br>" + value[0];
          }
        );
        newCitation.style.backgroundColor = "white";
        newCitation.style.marginBottom = "7px";
        newCitation.style.padding = "6px";
        newCitation.style.boxShadow= "0 2px 6px rgba(0,0,0,0.4)";
        newCitation.style.borderRadius = "3px";
        document.getElementById("answerswered[]").appendChild(newCitation);
      }
    }

localForage建立在localStorage和朋友的基础上。重要的部分是它绑定到您访问它的源。

从内容脚本使用它会使用网站的源,例如,在http://example.com/test上使用扩展会将数据绑定到http://example.com/源,而在http://example2.com/test上使用扩展会将数据绑定到附加到源http://example2.com/的完全独立的存储。更重要的是,数据与页面自己的存储共享(并可能干扰)。

因此,使用 localStorage(以及扩展的 localForage)不允许在内容脚本中产生预期的结果(尽管如果您尝试操作页面自己的存储,它可能仍然有用)。

因此,有两种可能性可以正确执行此操作:

  1. 如果必须使用它,请在后台脚本中使用localForage。在这种情况下,数据将绑定到源chrome-extension://yourextensionidhere。但是,这无法从内容脚本访问 - 您需要使用消息传递传递数据,这很烦人。

  2. 更好的特定于扩展的方法:使用本机 chrome.storage API,该 API 在扩展的所有部分之间共享。此 API 专门用于解决需要传递数据的限制等。

  3. (赢得大量互联网积分的方法)使用 chrome.storage API 为 localForage 编写自定义驱动程序。这将允许人们轻松地在Chrome扩展程序和应用程序中使用它。显然,这是已经尝试过的事情。

这个问题可能有用。