Search code examples
jqueryfirefoxfirefox-addonfirefox-addon-sdkbrowser-addons

Addon sdk open new tab with pre-appended image/html


In firefox addon, I have main.js code :

var button = ToggleButton({
  id: "ee-button",
  label: "EE button",
  icon: {
    "16": "./icon-16.png",
    "32": "./icon-32.png",
    "64": "./icon-64.png"
  },
  onChange: captureVisibleTab
});

And within this file : (Ref : Tab screenshot)

function captureVisibleTab() {
  .
  . 
  .
  .
  var canvas = contentDocument.createElement('canvas');
  canvas.style.maxwidth = region.width + "px";
  canvas.style.maxheight = region.height + "px";
  canvas.width = region.width;
  canvas.height = region.height;
  var ctx = canvas.getContext('2d');
  ctx.clearRect(region.x, region.y, region.width, region.height);
  ctx.drawWindow(contentWindow, region.x, region.y, region.width, region.height, backgroundColor);
  var url = canvas.toDataURL(); 

  tabs.open({
  url: self.data.url("test.html"),
  isPinned: false,
  onOpen: function onOpen(tab) {
  },
  onReady: function(tab)
  {
    console.log('canvas : ' + (JSON.stringify(url)) );
    tab.attach({
    contentScript: 'document.body.style.border = "5px solid red"; document.body.appendChild("Test")'
    });
  }
  });  
  return url;
}

I need to open a new tab with this image appended in the html.
* Tried : window.open => window not defined
* Tried : contentScript:'document.body.style.border = "5px solid red";' => works
* Tried : contentScript: 'document.body.style.border = "5px solid red"; document.body.appendChild("Test")' => error :

  Message: TypeError: Argument 1 of Node.appendChild is not an object.
  Stack:   @javascript:document.body.style.border = "5px solid red"; document.body.appe
ndChild("Test"):1:47

Solution

  • for a url just use data url with html like this:

    var escapedHtml = escape('<b>rawr</b><img src="blah">')
    var url = 'data:text/html,' + escapedHtml
    

    or so you dont have an ugly url in the bar, make your html a blob and load the blob url like this:

    var {Blob, File} = Cu.import("resource://gre/modules/Services.jsm", {});
    var oFileBody = '<a id="a"><b id="b">hey!</b></a>'; // the body of the new file...
    var oBlob = Blob([oFileBody], { type: "text/html"});
    var blobUrl = URL.createObjectURL(oBlob); //returns a string like blob:null/bbe1b94e-0800-4af2-9d9e-df09c0b9cab3 so paste that into your url bar