For research purposes, I am trying to write a web-extension that override some part of the web APIs (for example setItem
, getItem
, or removeItem
from the Storage
interface).
Unfortunately, when trying the following:
index.js
Storage.prototype.setItem = function(a, b) { return 42; }
manifest.json
{
"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"]
}]
}
Then using web-ext run
, and opening Firefox's WebConsole after loading any webpage.
$ window.localStorage.setItem(1, 2)
undefined
I would have hoped it to return 42
.
What happened?
You need to run the code via window.eval()
to access the context of the web page itself. For example:
browser.tabs.executeScript(1, {
code: 'window.eval("Storage.prototype.setItem = function(a, b) { return 42; }")'
})