Add: msg.sendBg

This commit is contained in:
eight 2018-10-06 11:43:42 +08:00
parent 171339f710
commit 05d582c726

View File

@ -28,12 +28,13 @@ const msg = (() => {
return { return {
send, send,
sendTab, sendTab,
sendBg,
broadcast, broadcast,
broadcastTab, broadcastTab,
broadcastExtension: send, // alias of send broadcastExtension: send, // alias of send
onMessage, on,
onTabMessage, onTab,
onExtensionMessage onExtension
}; };
function send(data, target = 'extension') { function send(data, target = 'extension') {
@ -56,6 +57,23 @@ const msg = (() => {
.then(unwrapData); .then(unwrapData);
} }
function sendBg(data) {
// always wrap doSend in promise
return preparing.then(doSend);
function doSend() {
if (bg) {
if (!bg._msg.handler) {
throw new Error('there is no bg handler');
}
const handlers = bg._msg.handler.extension.concat(bg._msg.handler.both);
return Promise.resolve(executeCallbacks(handlers, data, {url: location.href}))
.then(deepCopy);
}
return send(data);
}
}
function broadcast(data, filter) { function broadcast(data, filter) {
return Promise.all([ return Promise.all([
send(data, 'both').catch(console.warn), send(data, 'both').catch(console.warn),
@ -96,17 +114,17 @@ const msg = (() => {
}); });
} }
function onMessage(fn) { function on(fn) {
initHandler(); initHandler();
handler.both.push(fn); handler.both.push(fn);
} }
function onTabMessage(fn) { function onTab(fn) {
initHandler(); initHandler();
handler.tab.push(fn); handler.tab.push(fn);
} }
function onExtensionMessage(fn) { function onExtension(fn) {
initHandler(); initHandler();
handler.extension.push(fn); handler.extension.push(fn);
} }
@ -115,7 +133,7 @@ const msg = (() => {
if (handler) { if (handler) {
return; return;
} }
handler = { bg._msg.handler = handler = {
both: [], both: [],
tab: [], tab: [],
extension: [] extension: []
@ -123,6 +141,17 @@ const msg = (() => {
chrome.runtime.onMessage.addListener(handleMessage); chrome.runtime.onMessage.addListener(handleMessage);
} }
function executeCallbacks(callbacks, ...args) {
let result;
for (const fn of callbacks) {
const data = withPromiseError(fn, ...args);
if (data !== undefined && result === undefined) {
result = data;
}
}
return result;
}
function handleMessage(message, sender, sendResponse) { function handleMessage(message, sender, sendResponse) {
const handlers = message.target === 'tab' ? const handlers = message.target === 'tab' ?
handler.tab.concat(handler.both) : message.target === 'extension' ? handler.tab.concat(handler.both) : message.target === 'extension' ?
@ -141,13 +170,7 @@ const msg = (() => {
return response(); return response();
function response() { function response() {
let result; const result = executeCallbacks(handlers, message.data, sender);
for (const handle of handlers) {
const data = withPromiseError(handle, message.data, sender);
if (data !== undefined && result === undefined) {
result = data;
}
}
if (result === undefined) { if (result === undefined) {
return; return;
} }