I am using the Firefox Add-on SDK to create an extension and am performing a PageMod. This code is in main.js.

...
exports.main = function() {
  var pageMod = require("sdk/page-mod");

  pageMod.PageMod({
    include: "*",
    contentScriptWhen: 'end',
    contentStyleFile: [
      self.data.url("css/style.css"),
      self.data.url("css/font-awesome.css")
    ],
    contentScriptFile: [
      self.data.url("js/jquery.js"),
      self.data.url("js/spritzify.js")
    ],
    onAttach: function onAttach(worker) {
      worker.postMessage("Hello World");
    }
  });
};
...

my css/font-awesome.css gets loaded into the page although the font files do not.

@font-face {
  font-family: 'FontAwesome';
  src: url('fonts/fontawesome-webfont.eot?v=4.1.0');
  src: url('fonts/fontawesome-webfont.eot?#iefix&v=4.1.0') format('embedded-opentype'), url('fonts/fontawesome-webfont.woff?v=4.1.0') format('woff'), url('fonts/fontawesome-webfont.ttf?v=4.1.0') format('truetype'), url('fonts/fontawesome-webfont.svg?v=4.1.0#fontawesomeregular') format('svg');
  font-weight: normal;
  font-style: normal;
}

The fonts folder is in the data folder of my extension. Could someone please explain how I can load custom fonts into a webpage using PageMod!


Solution 1:

If you look into the console messages, this is what you should see:

downloadable font: download not allowed (font-family: "FontAwesome" style:normal weight:normal stretch:normal src index:0): bad URI or cross-site access not allowed

Unfortunately for you, web fonts are subject to the same-origin policy which can only be relaxed via CORS. This means that there is no way to load the font file from an extension URL as there is no way to use CORS there.

This leaves you with two options:

  1. You host the font on a web server with proper CORS headers or use some existing font hosting.
  2. You encode the font as a data: URI. There is a number of data: URI generators available, e.g. this one.

IMHO the second solution is the preferable one as your extension won't be dependent on any web servers, especially not third-party web servers. Also, it won't introduce any delays caused by font downloading. I tried it and it worked fine:

@font-face {
  font-family: 'FontAwesome';
  src: url('data:application/octet-stream;base64,d09GRgAB...') format('woff');
  font-weight: normal;
  font-style: normal;
} 

Side-note: You don't need the full backwards compatibility dance in a Firefox extension, it's sufficient to have the font in the WOFF format.