The callback of .get()
expects exactly 1 parameter.
By passing a function that takes 2 parameters (i.e. function(data, e) {...}
), you do the following:
- The function is called with one parameter. It is assigned to a callback-local variable
data
.
- The second parameter stays undefined. It is assigned to a callback-local variable
e
.
- If there was a variable
e
in the outer scope, it is no longer accessible.
I assume the part 3 is exactly your problem. You had a variable e
in the scope where you called .get()
, but you made it inaccessible.
Generally, due to the concept called closures, you don't actually need to pass e
inside the scope - you just use the variable from the outer scope, and it will be retained in memory until the function executes. Think of it as a "locally global" variable, if that makes any sense. If it doesn't, there are better explanations.
With that in mind:
chrome.storage.sync.get('privateKey', function(data) { // just don't mention e here
/* ... */
// Just use e inside if it comes from outer scope
var uncrypted = decrypt.decrypt(e.detail.encryptedVal);
/* ... */
});
Better yet, let's make that into a function:
function decryptValue(value, callback) {
chrome.storage.sync.get('privateKey', function(data) {
var decrypt = new JSEncrypt();
decrypt.setPrivateKey(data.privateKey);
var decrypted = decrypt.decrypt(value);
callback(decrypted);
}
}
/* ... */
decryptValue(e.detail.encryptedVal, function(decrypted) {
// Do something
});
/* ... */
Note that callback
variable? While you can use decrypted
inside the callback of .get()
, due to the fact it's asynchronous you can't use it outside. There is a very good overview of the problem, and another one here. Basically, .get()
is asynchronous so you HAVE to use a callback.
/* ... */
decryptValue(e.detail.encryptedVal, function(decrypted) {
// Do something with decrypted
});
// Here, decrypted is not yet computed
/* ... */
Most of Chrome API is asynchronous. I would recommend to read You Don't Know JS book on the topic.