Firefox Addon SDK: Loading addon file into iframe

firefox, firefox-addon, firefox-addon-sdk, iframe, javascript

Solution

I think I suggested in the bug or in the ML of jetpack a terrible workaround, that basically is convert your `resource://` in a `data:` url (using `data.load` to load the HTML content, and then encode and append as prefix, so something like that should works:

/* main.js */
const { data } = require('sdk/self');

// just an example, you can use `tab.attach` too
require('sdk/page-mod').PageMod({
  include: '*',
  contentScriptFile: data.url('content.js'),
  contentScriptOptions: {
    content: encodeURIComponent(data.load('index.html'))
  }
});

/* content.js */
let iframe = document.body.appendChild(document.createElement('iframe'));

iframe.setAttribute('sandbox', 'allow-scripts');
// maybe you want also use the seamless attribute, see:
// https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe

iframe.contentWindow.location.href = 'data:text/html;charset=utf-8,' + self.options.content;

It's a workaround of course, and I hope that the bug you mentioned will be fixed soon. Notice that in this way you cannot communicate directly from the iframe to the parent's document, but it means also that you can't do the way around, that is what you want to prevent.

Of course, you can still use the add-on code to communicate between your iframe and the parent's document (you need to attach content scripts and use `port` and `postMessage`).

Edit: changed the way the url is set, otherwise getting the `src` attribute from the parent's document is still possible, and contains whole HTML.

Problem

I want to load a `resource://` link, respectively a local file from my Firefox addon into an `iframe` in a web page. The reason is, that the resource should be visually embedded into the web page while not giving the website access to it's DOM for security reasons. The issue has been discussed in various places in the past, e.g. here (without solution): https://bugzilla.mozilla.org/show_bug.cgi?id=792479 As most of the postings are rather old, I want to ask, if in the meantime there are any new solutions or workarounds.

Original source