Help with understanding the Imagify extension examply by MDN

I have been trying to learn how to make add-ons for Firefox, and I have covered most of what I wanted to know, thanks to the excellent MDN pages.

The last hurdle is trying to figure out how to get the “background” script of my extension to communicate with the content script.

I tried following the few example extension that cover this background/content messaging concept and its not clear to me what is going on in them.

Take for example, the Imagify example. I cant tell for sure what .js files are “background” or “content” scripts. The extensions manifest file does not makes use of the "background": {} and "content_scripts": [] keys:

{
	"description": "Adds a sidebar offerin a file picker and drap and drop zone. When an image file is chosen the active tab's body content is replaced with file selected. See https://developer.mozilla.org/en-US/Add-ons/WebExtensions/Examples#imagify",
	"manifest_version": 2,
	"name": "Imagify",
	"version": "1.0",
	"homepage_url": "https://github.com/mdn/webextensions-examples/tree/master/imagify",
	"permissions": [
		"tabs",
		"<all_urls>"
	],
	"sidebar_action": {
		"default_title": "Imagify",
		"default_panel": "sidebar/sidebar.html"
	},
	"web_accessible_resources": [
		"/viewer.html"
	]
}

In fact no .js files are mentioned, yet it seems to work when I try it.

What I mean to ask is how does one know just by looking at the content inside the .js, under a extensions directory, if the file is a “background” or “content” script?
In the same Imagify example, there is a file, viewer.js, with the content:

const params = new URLSearchParams(window.location.search);
const imageBlobURL = params.get("blobURL");
document.querySelector("img").setAttribute("src", imageBlobURL);

I am thinking because of the line. document.querySelector("img"), it is safe to assume this is the content script?

Reading the MDN extensions section, only content scripts can directly do document.querySelector("img"), I am very new to JS/WebDev so I don’t know for sure, I hope I can know for sure here.

Any help would be greatly appreciated!

Background script is optional, not every extension needs one.

Regarding content scripts, they can be injected every time using the manifest file, but they can be also registered later on or they can be executed manually.
The example uses legacy “browser.tabs.executeScript”

It’s better to use modern Scripting API:


(requires “scripting” permission)

And lastly, make sure to read the docs so that you understand how the extensions works:

1 Like

This was much needed help as it clarifies quite a few things that had me going round in circles. Thank you

I had no idea you could execute “content” scripts from a ‘background’ script. Makes life a whole lot easier, for not at least.

I will go over the Extensions module on MDN now.

Cheers for this.

1 Like