google-chromegoogle-chrome-extensiongoogle-chrome-storage

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


Solution

  • 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);    
    };