尝试在contentScript中调用函数时,“函数未定义”

时间:2014-12-29 17:06:48

标签: javascript firefox-addon-sdk

插件代码,创建Panel onShow(),从本地文件系统读取文件列表并填充到Panel 点击文件名旁边的<img>时,我试图致电Namespace.load(),向我的插件代码发送消息,但我得到Namespace is not defined

任何想法为什么?

Data.js

var data = require("sdk/self").data;
exports.get = function(content) {
    return data.url(content);
};

main.js

var Data = require("./Data");
var panel = Panel.Panel({
  width: 450,
  height: 300,
  contentURL: Data.get("html/view.html"),
  contentScriptFile: Data.get("js/controller.js"),
});

错误..

JavaScript error: resource://jid1-xqhae0e9m07ekq-at-jetpack/addon-firefox/data/html/view.html, line 1: Namespace is not defined

controller.js(contentScript)..

var Namespace = {
  load: function(filename) {
    self.port.emit("load", filename);
  }
};

self.port.on("uiData", function (uiData) {
  var parsed = JSON.parse(uiData),
    content = '';

  for (var i = 0; i < parsed.files.length; i++) {

    content = '<tr>';
    content += '<td>' + parsed.files[i] + '</td>';
    content += '<td><img onclick="Namespace.load(' + parsed.files[i] + ');" src="../images/load-24.png"></img>';
    content += '</td></tr>';

    document.getElementById('resultFiles').innerHTML += content;
  }

  document.getElementById("directory").value = parsed.directory;
});

2 个答案:

答案 0 :(得分:2)

已使用Components.utils.exportFunction,因为在FF30中针对内容脚本执行了环境更改,描述为here

var Namespace = {
  load: function(filename) {
    self.port.emit("load", filename);
  }
};

exportFunction(Namespace.load, unsafeWindow, {defineAs: "load"});

self.port.on("uiData", function (uiData) {
  var parsed = JSON.parse(uiData),
    content = '';

  for (var i = 0; i < parsed.files.length; i++) {

    content = '<tr>';
    content += '<td>' + parsed.files[i] + '</td>';
    content += '<td><img onclick="window.load(\'' + parsed.files[i] + '\');" src="../images/load-24.png"></img>';
    content += '</td></tr>';

    document.getElementById('resultFiles').innerHTML += content;
  }

  document.getElementById("directory").value = parsed.directory;
});

答案 1 :(得分:1)

我认为工作代码如下:

var data = require("sdk/self").data;
var panel = Panel.Panel({
  width: 450,
  height: 300,
  contentURL: data.url("html/view.html"),
  contentScriptFile: data.url("js/controller.js"),
});

您可以通过self.data.url()获取给定文件的资源uris。有关详细信息,请参阅docs on panels