出于研究目的,我正在尝试编写一个覆盖Web API某些部分的Web扩展(例如,setItem
界面中的getItem
,removeItem
或Storage
。]
不幸的是,当尝试以下操作时:
index.js
Storage
manifest.json
Storage.prototype.setItem = function(a, b) { return 42; }
然后使用{
"manifest_version": 2,
"name": "cool-extension-name",
"version": "1.0",
"description": "A useful description.",
"icons": {"48": "icons/potatoes.jpg"},
"content_scripts": [{
"run_at": "document_start",
"matches": ["<all_urls>"],
"js": ["index.js"]
}]
}
,并在加载任何网页后打开Firefox的WebConsole。
web-ext run
我希望它返回$ window.localStorage.setItem(1, 2)
undefined
。发生了什么事?
您需要通过42
运行代码以访问网页本身的上下文。例如:
window.eval()
另请参见:browser.tabs.executeScript(1, {
code: 'window.eval("Storage.prototype.setItem = function(a, b) { return 42; }")'
})