What is the process for importing files in a Firefox extension (add-on)?

We have developed browser extensions for Chrome, Firefox, and Safari. The Firefox extension includes a tracker called tracker.js, which is accessed from the controller using this line of code:

tracker = require("../../firefox/tracker.js").tracker;

The tracker functionality relies on requiring other files such as:

if (typeof exports !== 'undefined') {
    common = require("../content/src/common.js").common;
    utils = require("../content/src/utils.js").utils;
}

var tracker = new function() {
    this.ws_track = function(params) {
        params["from_extension"] = true;
        params["platform"] = common.sys.platform;
        params["version"] = utils.get_version();
        if (params["e"] === "install") {
            utils.send_get_request(common.config.urls.apis.wstrack, params, function(data) {}, 'json');
        }
    };
};

if (typeof exports !== 'undefined') {
    exports.tracker = tracker;
}

However, I encountered an error when trying to require the controller file from the tracker:

JPM [error]   Message: TypeError: tracker is undefined

In this scenario, the tracker code looks like this:

if (typeof exports !== 'undefined') {
    common = require("../content/src/common.js").common;
    controller = require("../content/src/controller.js").controller;
    utils = require("../content/src/utils.js").utils;
}

var tracker = new function() {
    this.ws_track = function(params) {
        params["from_extension"] = true;
        params["platform"] = common.sys.platform;
        params["version"] = utils.get_version();
        var uid = controller.load_param("uid");
        if (uid) {
            params["uid"] = uid;
        }
        if (params["e"] === "install") {
            utils.send_get_request(common.config.urls.apis.wstrack, params, function(data) {}, 'json');
        }
    };
};

if (typeof exports !== 'undefined') {
    exports.tracker = tracker;
}

Not requiring the controller causes it to be undefined. How can I successfully require the controller from the tracker file? Combining the files is not an option since the controller file is utilized across all browsers, while each browser has its own unique tracker. (Mozilla did not approve our Chrome tracker).

Update: By moving the controller code to the controller itself and calling the tracker from there, I was able to resolve the issue (the tracker no longer depends on the controller). If you have any alternative solutions, please share them with me.

Answer №1

Utilizing a SDK require function is essential, and here's how I implement it: https://developer.mozilla.org/en-US/Add-ons/SDK/Low-Level_APIs/system_child_process#Using_child_process_in_non-jpm_extensions

// Incorporating SDK Components
const COMMONJS_URI = 'resource://gre/modules/commonjs';
const { require } = Cu.import(COMMONJS_URI + '/toolkit/require.js', {});
var child_process = require('sdk/system/child_process');

// Applying it similarly as demonstrated above

The functionality seems to be compatible with CommonJS modules; explore more here - https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Using#Importing_CommonJS_modules

Additionally, there exists a require feature in workers that can be utilized like so:

importScripts('resource://gre/modules/workers/require.js');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Filtering Items with Checkboxes in JavaScript

I'm currently working on creating a filter system using checkboxes. Here is an example of what I have: Red squares Red circles Blue squares Blue circles I am aiming to set up filters based on both color and shape. However, I am facing some challe ...

Having trouble with Angular JS functionality

Today is my first day diving into AngularJS and I'm eager to learn more! Despite grasping the concept of how model-controller-views operate in AngularJS, I encountered an issue where the variables are not displaying as expected. Instead of the values, ...

Content placed in a div element via JavaScript will not wrap onto a new line

I recently created a div using JavaScript with the code mydiv.textContent="blahblahblahblahblahblah";. Although I have set the width of mydiv to 100px, the text string assigned to the div continues to run in one line without dropping down to the next lin ...

Losing authentication token when refreshing with Nuxt asyncData and Axios

While testing a get API that retrieves an array of mail data through Postman, everything seems to be working smoothly. However, when I implement the asyncData method to fetch the array in my code, it only works once. Upon page refresh, I encounter a 401 er ...

Customers will refresh themselves whenever the supplier refreshes

After reading through the React documentation, it explains that re-rendering all consumers occurs each time the Provider is re-rendered due to a new object being created for value. To see this in action, I decided to create a simple example: class App ...

Determine whether there are three or more identical values when comparing two objects in typescript

Hello there, I am in need of some assistance as I am unsure where to begin. Any help would be greatly appreciated. Here are the two objects I have: const Questions = { five: "c" four: "c" one: "a" three: "a" two ...

Correctly referencing a variable in a delayed AJAX request is crucial for ensuring the proper execution

I am facing an issue with a function called fetchAlbum. This function sets up a placeholder, sends an AJAX request, and updates the placeholder upon success. Here is the code snippet: function fetchAlbum() { albumCounter++; var albumElement = $(&a ...

React's componentDidUpdate being triggered before prop change occurs

I am working with the CryptoHistoricGraph component in my app.js file. I have passed this.state.coinPrices as a prop for this element. import React from 'react'; import axios from 'axios'; import CryptoSelect from './components/cry ...

Understanding TypeScript typing when passing arguments to the Object.defineProperty function

After reviewing all the suggested answers, including: in Typescript, can Object.prototype function return Sub type instance? I still couldn't find a solution, so I'm reaching out with a new question. My goal is to replicate Infix notation in J ...

Issue with offset calculation in bootstrap table occurs when the bootstrap-table is closed and the window is resized

In a recent project, I utilized the bootstrap table. However, upon closing the bootstrap table with the following script: $(document).ready(function () { $(".removetable").click(function (e) { $(".table-aria").remove(); ...

What could be the reason for the Nextjs fetch request returning undefined data?

Here is the code snippet for my GET request in the API section: export default async (req, res) => { const { query: { className }, method } = req; switch (method) { case "GET": try { const classDetail = await Class.findO ...

What is the best way to implement an AJAX request to update the page without having to refresh it?

My to-do app currently reloads the page when I click on "Add" in order for the changes to take effect and display the items. However, I want to implement AJAX requests so that the page does not need to refresh. Can anyone guide me on how to achieve this? ...

Obtain all subelements from the entity

In my Vue project, I am attempting to collect and POST some values to the server. However, I am finding the current implementation to be somewhat frustrating. Within a Vue method, I have a function that POSTs the collected values from the original object: ...

Expo is having trouble locating the module "color-convert" - such a frustrating problem

Having an issue! I ran the command npm start in my terminal and received the following error: Starting project at /home/pc/Documents/Projects/Mobile/weather_app Developer tools running on http://localhost:19002 Cannot find module 'color-convert' ...

Encountering an error message stating "Unable to read property 'map' of undefined while attempting to create drag and drop cards

I have incorporated the library available at: https://github.com/clauderic/react-sortable-hoc The desired effect that I am aiming for can be seen in this example: https://i.stack.imgur.com/WGQfT.jpg You can view a demo of my implementation here: https:// ...

A useful guide on how to fetch information in the front end from res.send and dynamically generate a page for every item in the database

I have a variable named data which holds an Array where each item has a unique ID. app.get('/products/:id', function (req, res) { res.send(data.map(data => "" + data.id + "")) //retrieves data of the element in the Array ...

Struggling to update the state within a React component using the useEffect hook alongside the 'popstate' eventListener

I am facing an issue with a useEffect in React that involves a popstate eventListener. The eventListener works correctly when I navigate away from the page and then return using the back button. However, when I try to set state within the function attached ...

React Array Number Looping

I am working with an array let counterArray = [5]; Currently, I need to iterate through the array 5 times {counterArray .map(counter=> <span>Counter- {counter}</span> )} Right now, this code snippet just displays the counter. How can ...

Fixing SCRIPT1028 error in IE9 with the help of AngularJS

Utilizing AngularJS in my single-page application, I have a button defined as follows: <button class="btn btn-success" onclick="doSeekTo({{todo.position}});doPlay();"> When this button is clicked, it triggers the javascript function with the specif ...

Is AjaxMin's EvalTreatment changing the game for JavaScript minification?

While minifying my project using the AjaxMin.dll with the default settings on every build/deployment, I ran into a problem. One of our third-party JavaScript files contains an eval statement that references variables or parameters which, when minified, cau ...