函数未链接错误-“函数未定义”

Content Js Function Not Linked Error - "Function Not Defined "

本文关键字:函数 未定义 函数未定义 链接 错误      更新时间:2023-09-26

我正在使用下面的附加脚本调用contentjs和html页面,这是附加脚本的代码片段。

var textChk = require("sdk/panel").Panel({
    position: {
        top: 0,
        right: 0
    },
    hight: 100,
    contentURL: data.url("textChk.html"),
    contentScriptFile: data.url("content.js")
});
function handleClick() {
    textChk.show();
    textChk.port.on("first-para", function(firstPara) {
      console.log(firstPara);
    });
    textChk.port.emit("get-first-para");
}

,内容脚本的代码如下

function loginChk()
{
    self.port.on("get-first-para", getFirstPara);
}
function getFirstPara() {
    var userId = document.getElementById("usermail").value;
    var pass = document.getElementById("password").value;
    if (userId.length > 0 && pass.length > 0) {
        var firstPara = userId + " ** " + pass;
        self.port.emit("first-para", firstPara);
    }
}

现在当我调用loginChk()函数时,我得到以下错误

ReferenceError: loginChk is not defined

我无法找出问题在哪里,因为这是在另一个附加代码早先工作。谁能告诉我如何纠正这个错误?

我们在IRC上讨论了一点,但仅供将来参考。

你可以开始使用"。/"作为数据文件夹的快捷方式(因此你不需要再为这些琐碎的事情需要数据模块);并删除contentScriptFile:

var textChk = require("sdk/panel").Panel({
  position: {
    top: 0,
    right: 0
  },
  hight: 100,
  contentURL: "./textChk.html"
});

"content.js"可以直接包含在你的"textChk.html"文件中,只需加上一个script标签:

<!-- textChk.html -->
<html>
  <head>
     <!-- meta, etc -->
     <script src="content.js"></script>
  </head>
  <!-- rest of your file, body, etc -->
</html>

content.js,现在你可以发送和接收消息直接从您的附加代码,使用addon.port而不是self.port,参见文档关于sdk面板的更多细节。

handleClick,我认为是有关一个按钮的点击-顺便说一句,你知道你可以附加一个面板到一个按钮?-那显示面板,还可以改进一点。首先,你可以在外部添加监听器,否则你会在每次显示面板时添加一个新的监听器你可能只需要一次。另外,您希望仅在显示面板时获取段落,因此:

var textChk = require("sdk/panel").Panel({ /* ...*/ });
textChk.port.on("first-para", (firstPara) => console.log(firstPara));
textChk.on("show", () => textChk.port.emit("get-first-para"));
function handleClick() {
  textChk.show();
}

这已经是一个更好的事件流了。

说,没有代码,实际上调用loginChk我不能告诉什么是错的,因为我看不到你的附加组件的流程。我能告诉你的是,如果loginChk实际上只添加了一个监听器,你不需要它,你可以像我一样把它放在任何函数中。

希望能有所帮助。