Override Chrome Storage API

风流意气都作罢 提交于 2021-02-17 05:44:07

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/63870053/override-chrome-storage-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!