简体   繁体   English

在 JS 中从 chrome 扩展中保存和读取数据

[英]Saving and reading data from chrome extension in JS

Simple task.简单的任务。 User can enter their login to form inside of google chrome extension, click button - login, and I should save this login into storage.用户可以在 google chrome 扩展程序中输入他们的登录信息,单击按钮 - 登录,我应该将此登录信息保存到存储中。 Next time, when user will open extension- login should appear in the input.下一次,当用户打开扩展时,登录应该出现在输入中。 User can change it by entering new login end click button.用户可以通过输入新的登录结束单击按钮来更改它。 The problem is that getChanges does not receive anything.问题是 getChanges 没有收到任何东西。

HTML: HTML:

<!doctype html>
<html>
    <head>      
        <script src="jquery.min.js" type="text/javascript"></script>
    </head>
    <body>      
        <input type="text" id="login" placeholder="login">
        <button id="doLogin">Login</button>          
        <script src="popup.js"></script>  
    </body>
</html>

popup.js: popup.js:

document.getElementById("doLogin").addEventListener("click", doLogin);

var extratedLogin= getChanges('myLogin');
$('#login').val(extratedLogin);

function getChanges(name) {  
    chrome.storage.local.get(name, function(result) {
      console.log('myLogin= '+JSON.stringify(result));
      return result.key;
    });
}

function saveChanges(name,value) {   
    chrome.storage.local.set({name: value}, function() { 
        console.log('Settings saved for '+ name);
    });
}
function doLogin(){
    //do something
    saveChanges('myLogin', $('#login').val());
}

manifest.json: manifest.json:

"permissions": ["storage", ...]

Was error is syntax.错误是语法。 Here is right saving and loading这是正确的保存和加载

window.onload = function() {
        chrome.storage.local.get(['mylogin'], function(items) {
            console.log('Settings retrieved ', items);
            $('#login').val(items['mylogin']); 
        });
    }      

    function doLogin(){          
        chrome.storage.local.set({'mylogin': $('#login').val()}, function() { 
            console.log('Fields data was saved.');
        });
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM