|
export function createMessageDispatcher(identity, handler) { |
|
chrome.runtime.onMessage.addListener((msg, sender, respond) => { |
|
if (!Array.isArray(msg)) { return; } |
|
if (msg[0] === identity) { |
|
var method = msg[1]; |
|
var args = msg.slice(2); |
|
var thunk = (res) => res(handler[method].apply(handler, args)); |
|
|
|
// call the method, but do it via a thunk that's injected into a promise chain |
|
// that way, all errors are handled the same way, and we can use the normal response methods |
|
// this includes non-existant methods, bad arguments, etc. |
|
Promise.resolve({ then: thunk }) |
|
.then((value) => ({ state: "resolved", value })) |
|
.catch((error) => ({ state: "rejected", error })) |
|
.then(respond); |
|
|
|
return true; |
|
} |
|
}); |
|
} |
|
|
|
export function dispatchTabMessage(to, method, ...args) { |
|
return new Promise((resolve, reject) => { |
|
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { |
|
chrome.tabs.sendMessage(tabs[0].id, [to, method, ...args], (response) => { |
|
if (response === undefined) { return reject(chrome.runtime.lastError); } |
|
if (response.state === "rejected") { return reject(response.error); } |
|
if (response.state === "resolved") { return resolve(response.value); } |
|
|
|
console.log("Weird message response:", response); |
|
return reject("Unknown response object."); |
|
}); |
|
}); |
|
}); |
|
} |
|
|
|
export function dispatchExtMessage(to, method, ...args) { |
|
return new Promise((resolve, reject) => { |
|
chrome.runtime.sendMessage([to, method, ...args], (response) => { |
|
if (response === undefined) { return reject(chrome.runtime.lastError); } |
|
if (response.state === "rejected") { return reject(response.error); } |
|
if (response.state === "resolved") { return resolve(response.value); } |
|
|
|
console.log("Weird message response:", response); |
|
return reject("Unknown response object."); |
|
}); |
|
}); |
|
} |