javascript 参考错误:需要未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24412124/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ReferenceError: require is not defined
提问by Sriram Sridharan
I'm currently working on a Mozilla Firefox addon.
我目前正在开发 Mozilla Firefox 插件。
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.
我已经设置了一个面板并附加了一个内容脚本。我需要在内容脚本和 main.js 之间进行通信。为此,我正在使用 addon-sdk 的端口 API。但是出于某种原因,我什至无法在两者之间获得简单的信息。
I am constantly receiving the following error when I test my addon using cfx: "ReferenceError: require is not defined"
当我使用 cfx 测试我的插件时,我不断收到以下错误:“ReferenceError: require is not defined”
Any idea what's wrong?
知道出了什么问题吗?
popup.js
弹出窗口.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
main.js 不会抛出相同的错误
Anybody experienced this before?
有没有人经历过这个?
回答by nmaier
Content scripts do not have access to require
. Instead self
is already declared.
内容脚本无权访问require
. 而是self
已经声明。
Just remove the require
line from popup.js
(but not main.js
).
只需require
从popup.js
(但不是main.js
) 中删除该行。
See Communicating using "port".
请参阅使用“端口”进行通信。