Browse Source

refactor: use sendTabCmd for tabs/frames

tophf 5 years ago
parent
commit
556de9f9b1

+ 3 - 6
src/background/sync/base.js

@@ -1,12 +1,12 @@
 import {
-  debounce, normalizeKeys, request, noop, makePause, ensureArray,
+  debounce, normalizeKeys, request, noop, makePause, ensureArray, sendCmd,
 } from '#/common';
 import { TIMEOUT_HOUR } from '#/common/consts';
 import {
   objectGet, objectSet, objectPick, objectPurify,
 } from '#/common/object';
 import {
-  getEventEmitter, getOption, setOption, hookOptions, sendMessageOrIgnore,
+  getEventEmitter, getOption, setOption, hookOptions,
 } from '../utils';
 import {
   sortScripts,
@@ -189,10 +189,7 @@ function extendService(options) {
 }
 
 const onStateChange = debounce(() => {
-  sendMessageOrIgnore({
-    cmd: 'UpdateSync',
-    data: getStates(),
-  });
+  sendCmd('UpdateSync', getStates());
 });
 
 export const BaseService = serviceFactory({

+ 3 - 11
src/background/utils/notifications.js

@@ -1,4 +1,4 @@
-import { i18n, defaultImage, noop } from '#/common';
+import { i18n, defaultImage, sendTabCmd } from '#/common';
 import { commands } from './message';
 
 const openers = {};
@@ -20,22 +20,14 @@ Object.assign(commands, {
 browser.notifications.onClicked.addListener((id) => {
   const openerId = openers[id];
   if (openerId) {
-    browser.tabs.sendMessage(openerId, {
-      cmd: 'NotificationClick',
-      data: id,
-    })
-    .catch(noop);
+    sendTabCmd(openerId, 'NotificationClick', id);
   }
 });
 
 browser.notifications.onClosed.addListener((id) => {
   const openerId = openers[id];
   if (openerId) {
-    browser.tabs.sendMessage(openerId, {
-      cmd: 'NotificationClose',
-      data: id,
-    })
-    .catch(noop);
+    sendTabCmd(openerId, 'NotificationClose', id);
     delete openers[id];
   }
 });

+ 4 - 9
src/background/utils/requests.js

@@ -1,5 +1,5 @@
 import {
-  getUniqId, request, i18n, isEmpty, noop,
+  getUniqId, request, i18n, isEmpty, sendTabCmd,
 } from '#/common';
 import { objectPick } from '#/common/object';
 import ua from '#/common/ua';
@@ -25,14 +25,9 @@ Object.assign(commands, {
     return id;
   },
   HttpRequest(details, src) {
-    httpRequest(details, src, (res) => (
-      browser.tabs.sendMessage(src.tab.id, {
-        cmd: 'HttpRequested',
-        data: res,
-      }, {
-        frameId: src.frameId,
-      })
-      .catch(noop)
+    const { tab, frameId } = src;
+    httpRequest(details, src, res => (
+      sendTabCmd(tab.id, 'HttpRequested', res, { frameId })
     ));
   },
   AbortRequest(id) {

+ 2 - 6
src/background/utils/tabs.js

@@ -1,4 +1,4 @@
-import { noop, getActiveTab } from '#/common';
+import { getActiveTab, sendTabCmd } from '#/common';
 import ua from '#/common/ua';
 import { commands } from './message';
 
@@ -39,11 +39,7 @@ ua.ready.then(() => {
 browser.tabs.onRemoved.addListener((id) => {
   const openerId = openers[id];
   if (openerId) {
-    browser.tabs.sendMessage(openerId, {
-      cmd: 'TabClosed',
-      data: id,
-    })
-    .catch(noop);
+    sendTabCmd(openerId, 'TabClosed', id);
     delete openers[id];
   }
 });

+ 6 - 10
src/background/utils/update.js

@@ -1,9 +1,11 @@
-import { i18n, request, compareVersion } from '#/common';
+import {
+  i18n, request, compareVersion, sendCmd,
+} from '#/common';
 import { CMD_SCRIPT_UPDATE } from '#/common/consts';
 import { getScriptById, getScripts, parseScript } from './db';
 import { parseMeta } from './script';
 import { getOption, setOption } from './options';
-import { commands, notify, sendMessageOrIgnore } from './message';
+import { commands, notify } from './message';
 
 Object.assign(commands, {
   CheckUpdate(id) {
@@ -72,13 +74,7 @@ async function downloadUpdate(script) {
   if (!updateURL) throw false;
   let checkingMeta = true;
   const update = {};
-  const msg = {
-    cmd: CMD_SCRIPT_UPDATE,
-    data: {
-      where: { id: script.props.id },
-      update,
-    },
-  };
+  const result = { update, where: { id: script.props.id } };
   announce(i18n('msgCheckingForUpdate'));
   try {
     const { data } = await request(updateURL, OPTIONS.meta);
@@ -106,6 +102,6 @@ async function downloadUpdate(script) {
       // `null` is sendable in Chrome unlike `undefined`
       error: error?.url || error || null,
     });
-    sendMessageOrIgnore(msg);
+    sendCmd(CMD_SCRIPT_UPDATE, result);
   }
 }

+ 3 - 8
src/background/utils/values.js

@@ -1,4 +1,4 @@
-import { noop } from '#/common';
+import { sendTabCmd } from '#/common';
 import { getValueStoresByIds, dumpValueStores, dumpValueStore } from './db';
 import { commands } from './message';
 
@@ -96,12 +96,7 @@ function broadcastUpdates(updates) {
   if (updates) {
     const updatedOpeners = Object.keys(updates)
     .reduce((map, scriptId) => Object.assign(map, openers[scriptId]), {});
-    Object.keys(updatedOpeners).forEach((openerId) => {
-      browser.tabs.sendMessage(+openerId, {
-        cmd: 'UpdatedValues',
-        data: updates,
-      })
-      .catch(noop);
-    });
+    Object.keys(updatedOpeners)
+    .forEach(openerId => sendTabCmd(+openerId, 'UpdatedValues', updates));
   }
 }

+ 17 - 0
src/common/index.js

@@ -34,10 +34,27 @@ export function initHooks() {
   return { hook, fire };
 }
 
+/**
+ * @param {string} cmd
+ * @param data
+ * @param {{retry?: boolean, ignoreError?: boolean}} [options]
+ * @return {Promise}
+ */
 export function sendCmd(cmd, data, options) {
   return sendMessage({ cmd, data }, options);
 }
 
+/**
+ * @param {number} tabId
+ * @param {string} cmd
+ * @param data
+ * @param {{frameId?: number}} [options]
+ * @return {Promise}
+ */
+export function sendTabCmd(tabId, cmd, data, options) {
+  return browser.tabs.sendMessage(tabId, { cmd, data }, options).catch(noop);
+}
+
 // ignoreError is always `true` when sending from the background script because it's a broadcast
 export async function sendMessage(payload, { retry, ignoreError } = {}) {
   if (retry) return sendMessageRetry(payload);

+ 4 - 5
src/popup/views/app.vue

@@ -106,7 +106,9 @@
 <script>
 import Tooltip from 'vueleton/lib/tooltip/bundle';
 import options from '#/common/options';
-import { getLocaleString, i18n, sendCmd } from '#/common';
+import {
+  getLocaleString, i18n, sendCmd, sendTabCmd,
+} from '#/common';
 import Icon from '#/common/ui/icon';
 import { store } from '../utils';
 
@@ -234,10 +236,7 @@ export default {
       window.close();
     },
     onCommand(id, cap) {
-      browser.tabs.sendMessage(this.store.currentTab.id, {
-        cmd: 'Command',
-        data: `${id}:${cap}`,
-      });
+      sendTabCmd(store.currentTab.id, 'Command', `${id}:${cap}`);
     },
     onToggleScript(item) {
       const { data } = item;