chrome.storage.local.set不会在本地保存数据

时间:2014-02-16 23:14:05

标签: javascript google-chrome google-chrome-extension local-storage

我正在尝试构建一个chrome扩展,我必须在本地存储一些数据。下面给出的代码是我的popup.html,我无法理解为什么这不会在本地存储中设置值。我的manifest.json具有“存储”和“标签”权限。

<script type="text/javascript">
function save() {
  var username = document.getElementById('username').value;
  var password = document.getElementById('password').value;
  chrome.storage.local.set({'username': username}, function(){});
  chrome.storage.local.set({'password': password}, function(){}); 
}
</script>
Roll Number
<input type="text" name="username" id="username"></input>
Password
<input type="password" name="password" id="password"></input>
<button onclick="save()" type="submit" name="submit">Save</button>

这是我的manifest.json文件。

{
  "manifest_version": 2,

  "name": "Autologin",
  "description": "Blah bhla.",
  "version": "1.0",
  "permissions": [
    "http://xxxxxxxxxxxxx/*",
    "storage"
  ],
  "content_scripts": [
    {
      "matches": ["http://xxxxxxxxxxxxx/*"],
      "js": ["autologin.js"]
    }
  ],
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "autologin.html"
  }
}

2 个答案:

答案 0 :(得分:1)

您需要通过创建popup.js将脚本部分移出html并将其包含在您的HTML中。

popup.js

function save() {
  var username = document.getElementById('username').value;
  var password = document.getElementById('password').value;
  chrome.storage.local.set({
   'username': username ,
   'password': password
  }, function(){});

}

document.getElementByName("submit").onclick=save;

popup.html

将那一堆<script>...</script>替换为<script src=popup.js></script>

manifest.json

"default_popup": "popup.html" //the name of your popup html file

答案 1 :(得分:-1)

试试这个,它对我有用

var dataObj = {}; dataObj[username] = username; dataObj[password] = password; chrome.storage.local.set(dataObj, function() {});