chrome.storage.local.set doesn't save data loc

2019-08-02 19:22发布

This question already has an answer here:

I'm trying to build a chrome extension in which I have to store some data locally. Code given below is my popup.html and I can't understand why this doesn't set values in local storage. My manifest.json has "storage" and "tabs" permission.

<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>

This is my manifest.json file.

{
  "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条回答
Animai°情兽
2楼-- · 2019-08-02 20:03

Try this, It worked for me

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

查看更多
smile是对你的礼貌
3楼-- · 2019-08-02 20:13

You need to move the script part out of html by creating a popup.js and include it in your html.

In 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;

In popup.html

Replace that bunch of <script>...</script> as <script src=popup.js></script>

In manifest.json

"default_popup": "popup.html" //the name of your popup html file
查看更多
登录 后发表回答