Search code examples
javascriptfirefox-addonfirefox-addon-webextensions

How to override functions from the Web API when writing a Firefox addon?


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?


Solution

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

    See also: https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts#Using_eval_in_content_scripts