Relative image url in content script in Firefox Add

I'm currently developing a Firefox extension using Add-On SDK and bumped into a real problem. Basically my extension just injects a content script into a webpage like this:

main.js

var pageMod = require("page-mod");
var self = require("self");

pageMod.PageMod({
  include: "http://mail.google.com/mail/*",
  contentScriptFile: [self.data.url("jquery.js"),
                      self.data.url("start.js")],
  attachTo : ["top"]
});

start.js

$('body').append('<div>1</div><img src="insertnote.png" /><div>2</div>');

Both start.js and insertnote.png are located in the data folder. Everything works except for the image. I just could't find how to get the real url for the image tag. Relative url doesn't seem to be working. :(

Is that even possible to include the addon's inner images inside content scripts or should I just use absolute urls to my webserver?


The following code should work

main.js

var pngurl = self.data.url("insertnote.png");

//inside PageMod constructor
onAttach: function(worker) {
  worker.port.emit("imageurl",pngurl);
}

start.js

self.port.on("imageurl", function(imgurl){
  var img = document.createElement("img");
  img.src = imgurl;
  document.body.appendChild(img);
});

Naturally it would be more efficient to pass just one object containing every asset's url.


You can use "contentScriptOptions" to pass the values into the content scripts.

main.js

var pageMod = require("sdk/page-mod");
var self = require("sdk/self");
pageMod.PageMod({
  include: "http://mail.google.com/mail/*",
  contentScriptFile: [self.data.url("jquery.js"),
                      self.data.url("start.js")],
  attachTo : ["top"],
  contentScriptOptions: {
    pngUrl: self.data.url("insertnote.png")
  }
});

start.js

$('body').append('<div>1</div><img src="' + self.options.pngUrl + '" /><div>2</div>');

The problem is that relative URLs are interpreted relative to the document, which in this case is the page, since you're putting the directly into the page, as a string.

In general, pages can link to images in an add-on if the add-on explicitly says so; they have to use the appropriate chrome:// URI to do that.

链接地址: http://www.djcxy.com/p/45748.html

上一篇: 如何从内容脚本发送消息到面板?

下一篇: Firefox添加内容脚本中的相对图像网址