diff --git a/browser.js b/browser.js index 045d523..e223c63 100644 --- a/browser.js +++ b/browser.js @@ -7,7 +7,7 @@ var EC = require("elliptic").ec; var ec = new EC("secp256k1"); -var cryptoObj = window.crypto || window.msCrypto || {}; +var cryptoObj = global.crypto || global.msCrypto || {}; var subtle = cryptoObj.subtle || cryptoObj.webkitSubtle; function assert(condition, message) { @@ -18,7 +18,7 @@ function assert(condition, message) { function randomBytes(size) { var arr = new Uint8Array(size); - window.crypto.getRandomValues(arr); + global.crypto.getRandomValues(arr); return new Buffer(arr); } diff --git a/index.js b/index.js index fa0f728..017a646 100644 --- a/index.js +++ b/index.js @@ -9,10 +9,17 @@ var promise = typeof Promise === "undefined" ? require("es6-promise").Promise : Promise; var crypto = require("crypto"); -// TODO(Kagami): We may fallback to pure JS implementation -// (`browser.js`) if this modules are failed to load. -var secp256k1 = require("secp256k1"); -var ecdh = require("./build/Release/ecdh"); +// try to use secp256k1, fallback to browser implementation +try { + var secp256k1 = require("secp256k1"); + var ecdh = require("./build/Release/ecdh"); +} catch (e) { + if (process.env.ECCRYPTO_NO_FALLBACK) { + throw e; + } else { + return (module.exports = require("./browser")); + } +} function assert(condition, message) { if (!condition) { diff --git a/package.json b/package.json index cf334f7..42117e8 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,7 @@ "browser": "browser.js", "scripts": { "install": "node-gyp rebuild || exit 0", - "test": "mocha && xvfb-run -a karma start && jshint .", + "test": "ECCRYPTO_NO_FALLBACK=1 mocha && xvfb-run -a karma start && jshint .", "m": "mocha", "k": "xvfb-run -a karma start", "kc": "xvfb-run -a karma start --browsers Chromium",