I think the documentation for chrome.storage
API (here) is currently not clear. I'm using this code to add a listener:
chrome.storage.onChanged.addListener(function(changes, namespace) {
for (key in changes) {
var storageChange = changes[key];
console.log('Storage key "%s" in namespace "%s" changed. ' +
'Old value was "%s", new value is "%s".',
key,
namespace,
storageChange.oldValue,
storageChange.newValue);
}
});
But how do i remove this listener? How to use the chrome.storage.onChanged.removeListener()
method?
I think the documentation for chrome.storage
API (here) is currently not clear. I'm using this code to add a listener:
chrome.storage.onChanged.addListener(function(changes, namespace) {
for (key in changes) {
var storageChange = changes[key];
console.log('Storage key "%s" in namespace "%s" changed. ' +
'Old value was "%s", new value is "%s".',
key,
namespace,
storageChange.oldValue,
storageChange.newValue);
}
});
But how do i remove this listener? How to use the chrome.storage.onChanged.removeListener()
method?
2 Answers
Reset to default 5The chrome.storage.onChanged.removeListener
takes the listener function you added as an input, so to remove it later, you have to store the function in a variable. Following code will work:
var myListenerFunction = function(changes, namespace) {
for (key in changes) {
var storageChange = changes[key];
console.log('Storage key "%s" in namespace "%s" changed. ' +
'Old value was "%s", new value is "%s".',
key,
namespace,
storageChange.oldValue,
storageChange.newValue);
}
};
// Add listener
chrome.storage.onChanged.addListener(myListenerFunction);
// Change value, will show output in console.log
chrome.storage.sync.set({'value': 'asd'});
// Remove listener
chrome.storage.onChanged.removeListener(myListenerFunction);
// Change value, will NOT show output in console.log as listener was removed
chrome.storage.sync.set({'value': 'asd123'});
Additional reading - The Events part of the Chrome extensions spec - https://developer.chrome./extensions/events
I didn't see chrome.storage.onChanged.removeListener in the page you provided.
Could you try assigning the callback function into a variable and pass it to AddListener. Then use that to remove
var changeListener = function(changes, namespace) {
for (key in changes) {
var storageChange = changes[key];
console.log('Storage key "%s" in namespace "%s" changed. ' +
'Old value was "%s", new value is "%s".',
key,
namespace,
storageChange.oldValue,
storageChange.newValue);
}
};
chrome.storage.onChanged.removeListener(changeListner);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745339545a4623261.html
评论列表(0条)