Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions decls/vars.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ declare var chrome: {
sender: ?string,
cb: (res: any) => void
) => ?boolean) => void
},
onDisconnect: {
addListener: (handler: () => ?boolean) => void
}
}
};
19 changes: 18 additions & 1 deletion src/ui-store.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {

let listeners = [];
let state;
let onDisconnect;

function handleMessage(msg: Object): void {
if (msg.type === UPDATE_STATE) {
Expand All @@ -17,6 +18,12 @@ function handleMessage(msg: Object): void {
}
}

function handleDisconnect(): void {
if (onDisconnect) {
onDisconnect();
}
}

function subscribe(listener: EmptyFunc): EmptyFunc {
listeners.push(listener);

Expand All @@ -38,13 +45,23 @@ function getState(): Object {
return state;
}

export default function (): Promise<Store> {
export default function (options?: {
onDisconnect?: EmptyFunc,
} = {}): Promise<Store> {
if (options.hasOwnProperty('onDisconnect') && typeof options.onDisconnect !== 'function') {
return Promise.reject(new Error('Expected the "onDisconnect" to be a function.'));
}

onDisconnect = options.onDisconnect;

// connect to "background" store
const connection = chrome.runtime.connect({name: CONNECTION_NAME});

// listen for changes in the "background" store
connection.onMessage.addListener(handleMessage);

connection.onDisconnect.addListener(handleDisconnect);

// return promise to allow getting current state of "background" store
return new Promise(resolve => {
chrome.runtime.sendMessage({type: UPDATE_STATE}, res => {
Expand Down
3 changes: 3 additions & 0 deletions tests/ui-store.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ async function createStore(state) {
const connection = {
onMessage: {
addListener: jest.fn()
},
onDisconnect: {
addListener: jest.fn()
}
};

Expand Down