ReferenceError: require is not defined

Sriram Sridharan picture Sriram Sridharan · Jun 25, 2014 · Viewed 17.9k times · Source

I'm currently working on a Mozilla Firefox addon.

I have set up a panel and attached a content script to it. I need to communicate between the content scripts and main.js. I'm using the port api of the addon-sdk for this. However for some reason, I can't even get a simple message through between the two.

I am constantly receiving the following error when I test my addon using cfx: "ReferenceError: require is not defined"

Any idea what's wrong?

popup.js

var self = require("sdk/self");
self.port.on("dataToPopup", function (data) { 
$("p.test").text(data);
});

The error is thrown for the first line itself.

main.js

var { ToggleButton } = require('sdk/ui/button/toggle');
var self = require("sdk/self");

var button = ToggleButton({
    id: "my-button",
    label: "my button",
    icon: {
        "16": "./images/tsfm16px.png"
    },
    onChange: handleChange
});

var panel = require("sdk/panel").Panel({
    contentURL: self.data.url("html/popup.html"),
    contentScriptFile: [self.data.url("scripts/jquery-1.9.1.min.js"), self.data.url("scripts/jquery-ui.js"), self.data.url("scripts/popup.js")],    
    onHide: handleHide
});

function handleChange(state) {
    if (state.checked) {
        panel.show({
            position: button
        });
    console.log("panel opened");    
    }
}

function handleHide() {
    button.state('window', {checked: false});
    console.log("panel closed");
}

panel.on("show", function() {
    panel.port.emit("dataToPopup", "flow");
    console.log("data sent");
});

The same error is not being thrown for main.js

Anybody experienced this before?

Answer

nmaier picture nmaier · Jun 25, 2014

Content scripts do not have access to require. Instead self is already declared.

Just remove the require line from popup.js (but not main.js).

See Communicating using "port".