UNPKG

@dioxide-js/detect-provider

Version:

A tiny utility for detecting the Dioxide-wallet provider which injected at window.dioxide.

60 lines (56 loc) 2.23 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.dioxideDetectProvider = factory()); }(this, (function () { 'use strict'; /** * Returns a Promise that resolves to the value of window.dioxide if it is * The Promise will not reject, but an error will be thrown if invalid options * are provided. * * @param options - Options bag. * @param options.timeout - Milliseconds to wait for 'dioxide#initialized' to * be dispatched. Default: 3000 * @returns A Promise that resolves with the Provider if it is detected within * given timeout, otherwise null. */ function detectDioxideProvider(_a) { var _b = _a === void 0 ? {} : _a, _c = _b.timeout, timeout = _c === void 0 ? 3000 : _c; if (typeof timeout !== 'number') { throw new Error("@duiyuan/detect-provider: Expected option 'timeout' to be a number."); } var done = false; return new Promise(function (resolve) { // Resolve promise immediately when detect window.dioxide // Otherwise detect it after dioxide#initialized event trigger, you will got null after given timeout if (window.dioxide) { detect(); } else { window.addEventListener('dioxide#initialized', detect, { once: true, }); setTimeout(function () { detect(); }, timeout); } function detect() { if (done) { return; } done = true; window.removeEventListener('dioxide#initialized', detect); if (window.dioxide) { resolve(window.dioxide); } else { var message = 'Unable to detect window.dioxide'; console.error('@dioxide/detect-provider:', message); resolve(null); } } }); } return detectDioxideProvider; }))); //# sourceMappingURL=detect-provider.umd.js.map