UNPKG

redux-ext

Version:

This simple package allow you to use Redux store all across the webextension.

100 lines (82 loc) 2.49 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _constants = require('../constants'); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } // const dispatchResponder = (action, send) => { // return true; // }; var MainStore = function MainStore(store, name) { var _this = this; _classCallCheck(this, MainStore); this.dispatch = function (action) { return _this.store.dispatch(action); }; this.getState = function () { return _this.store.getState(); }; this.replaceReducer = function (newReducer) { return _this.store.replaceReducer(newReducer); }; this.subscribe = function (observer) { return _this.store.subscribe(observer); }; this.store = store; this.name = name; _constants.webextApi.runtime.onMessage.addListener(function (request, sender, sendResponse) { if (request && request._type && request._name && request._name === _this.name) { switch (true) { case request._type === _constants.DISPATCH: var action = Object.assign({}, request._data, { sender: sender }); _this.store.dispatch(action); // dispatchResponder(action, sendResponse); break; case request._type === _constants.STATE: sendResponse(_this.store.getState()); break; default: break; } } }); this.store.subscribe(function () { _constants.webextApi.tabs.query({}, function (tabs) { var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = tabs[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var tab = _step.value; _constants.webextApi.tabs.sendMessage(tab.id, { _type: _constants.STATE, _name: _this.name, _data: _this.store.getState() }); } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } }); _constants.webextApi.runtime.sendMessage({ _type: _constants.STATE, _name: _this.name, _data: _this.store.getState() }); }); if (_constants.browserName === 'safari') { window['__' + name] = this; } }; exports.default = MainStore;