简体   繁体   中英

'Function is not defined' when trying to call a function inside a contentScript

Addon code, creates a Panel .
onShow() , a list of files are read from local filesystem and populated into Panel .
When <img> next to a filename is clicked, I'm trying to call Namespace.load() , to send a message to my addon code, but i get Namespace is not defined .

Any ideas why?

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"),
});

Error ..

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;
});

Used Components.utils.exportFunction since there were changes to execute environment in FF30 for content scripts, described 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;
});

I think working code would look like:

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"),
});

You get the resource uris for a given file via self.data.url(). See the docs on panels for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM