Search code examples
javascriptfirefoxfirefox-addonfirefox-addon-sdk

Crypto getRandomValue in Firefox add-on content script


I need to use crypto.getRandomValue (MDN) in my Firefox add-on. But, I didn't find a way to have an access to crypto in my content script. Is there a way to do it?

update

I was mistaken, I've tried not in a content script, but directly in main.js. Do I need to use content script just for this function or it could be done without?


Solution

  • Works for me just fine... Maybe you misspelled getRandomValues as getRandomValue in your code as well.

    Content scripts

    var {PageMod} = require("sdk/page-mod");
    
    // Content scripts should be able to use crypto just fine.
    PageMod({
      include: "*",
      contentScript: 'console.log(crypto.getRandomValues(new Uint8Array(10)));'
    });
    

    Logs some random data, as expected.

    SDK modules, such as main.js

    // SDK modules do not have a window, but we can always borrow the
    // hidden window.
    
    var {Cu} = require("chrome");
    Cu.import("resource://gre/modules/Services.jsm");
    var window = Services.appShell.hiddenDOMWindow;
    console.log(window.crypto.getRandomValues(new Uint8Array(10)));
    

    Logs some random data, as expected.