简体   繁体   中英

Override Chrome Storage API

I would like to override chrome.storage.local.set in order to log the value of a storage key when the Chrome Storage API is called:

var storage_local_set = chrome.storage.local.set;
chrome.storage.local.set = function(key, value) {
    console.log(key);
    storage_local_set(key);    
}

But I get Illegal invocation: Function must be called on an object of type StorageArea when storage_local_set(key) gets called. How can I store the data after logging the key?

For chrome.storage.sync.set this is what I tried based on the solution given:

const api = chrome.storage.sync;
const { set } = api; 
api.set = function (data, callback) {
  console.log(data);
  set.apply(api, arguments);  
};

But this is not hooking the API

You need to use .call() or .apply() to provide this object:

storage_local_set.apply(this, arguments);

The parameters in your override don't match the documentation though. If you want to match the documentation then do it like this:

const api = chrome.storage.local;
const { set } = api; 
api.set = function (data, callback) {
  console.log(data);
  set.apply(api, arguments);    
};

And if you want to change the signature to separate key and value:

const api = chrome.storage.local;
const { set } = api; 
api.set = (key, value, callback) => {
  console.log(key, value);
  set.call(api, {[key]: value}, callback);    
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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