想要访问Chrome扩展程序的本地存储空间

时间:2016-06-22 09:36:30

标签: google-chrome-extension local-storage

我的manfiest.json就是这个。

    {
  "manifest_version": 2,

  "name": "GTmetrix Analyzer Plugin",
  "description": "This extension will analyze a page using GTmetrix",
  "version": "2.1",
  "options_page": "options.html",
  "browser_action": {
   "default_icon": "icon.png",
   "default_popup": "popup.html"
  },
  "background": {
    "scripts": ["background.js"],
    "persistent": false
  },
  "permissions": ["tabs", "storage"], 
  "content_scripts": [
      {
          "matches": ["http://ticketchest.geekschicagolabs.com/admin/orderHistory"],
          "css": ["mystyles.css"],
          "js": ["jqueryui-min.js", "content-script.js"]
      }
  ]
}

我的popup.html是

    <!doctype html>
<html>
  <head>
    <title>Ticket chest</title>
    <script src="popup.js"></script>
  </head>
  <body>
    <h1>Ticket chest extension</h1>
    <a href="options.html">Settings</a>
    <!-- <button id="checkPage">Check this page now!</button> -->
  </body>
</html>

和background.js是

    chrome.runtime.onMessage.addListener(function(response, sender, sendResponse){
 localStorage['privateKeyy'] = response;
});

现在我想要用户在文本区域中输入的内容,它还将保存在本地存储的本地存储空间中,它将保存在扩展本地存储中但不保存在网页中。

那是内容脚本代码

    window.onload = function() {

  document.getElementById('save').onclick = function(){
   var privateKey = document.getElementById("textarea").value;

   chrome.storage.sync.set({'privateKey':privateKey}, function(){
    //document.getElementById('privateKey').value = privateKey;
    //chrome.browserAction.setBadgeBackgroundColor({color:[200, 0, 0, 100]});
    //chrome.tabs.sendMessage(privateKey);
    chrome.storage.local.set({'privateKeyy':privateKey});
    localStorage.setItem("lastname", "Smith");
    alert('save successfully');
   });
   //syncStorage["privateKey"] = privateKey;
  }

  document.getElementById('erase').onclick = function(){
   chrome.storage.sync.remove('privateKey', function(){
    alert('erase successfully');
   });
  }

  document.getElementById('get').onclick = function(){
   chrome.storage.sync.get('privateKey', function(data){
    alert(data.privateKey);
    console.log(data.privateKey);
   });
  }

}

1 个答案:

答案 0 :(得分:3)

如果您希望将数据存储在网页的本地存储中,请将代码移至内容脚本(而不是在扩展程序的后台脚本中执行代码)。 另见:https://stackoverflow.com/a/23082216/4419582