覆盖 Chrome 存储 API

Override Chrome Storage API

我想覆盖 chrome.storage.local.set 以便在调用 Chrome 存储 API 时记录存储键的值:

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

但是当调用 storage_local_set(key) 时我得到 Illegal invocation: Function must be called on an object of type StorageArea。记录密钥后如何存储数据?

对于chrome.storage.sync.set,这是我根据给出的解决方案尝试的:

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

但这不是挂钩 API

您需要使用 .call() 或 .apply() 来提供 this 对象:

storage_local_set.apply(this, arguments);

不过,您覆盖中的参数与文档不匹配。如果你想匹配文档,那么这样做:

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

如果您想将签名更改为单独的键和值:

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