Skip to content

Commit

Permalink
use message broadcast in mv2
Browse files Browse the repository at this point in the history
  • Loading branch information
tophf committed Feb 14, 2025
1 parent 0a99788 commit eb6d6c4
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
23 changes: 22 additions & 1 deletion src/background/broadcast.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ import '@/js/browser';
import {kBroadcast} from '@/js/consts';
import {rxIgnorableError} from '@/js/msg-api';
import {chromeLocal, chromeSession} from '@/js/storage-util';
import {ownRoot} from '@/js/urls';
import {getWindowClients} from './util';

let toBroadcast;

export function broadcast(data) {
toBroadcast ??= (setTimeout(doBroadcast), []);
toBroadcast ??= (setTimeout(__.MV3 ? doBroadcast : doBroadcastMV2), []);
toBroadcast.push(data);
}

Expand All @@ -16,6 +18,25 @@ function doBroadcast() {
toBroadcast = null;
}

async function doBroadcastMV2() {
const jobs = [];
const [clients, tabs] = await Promise.all([
__.MV3 && getWindowClients(), // TODO: detect the popup in Chrome MV2 incognito window?
browser.tabs.query({}),
]);
const iActive = tabs.find(t => t.active);
const data = toBroadcast;
toBroadcast = null;
if (iActive > 0)
tabs.unshift(tabs.splice(iActive, 1)[0]);
if (!__.MV3 || clients[0])
jobs.push(broadcastExtension(data, true));
for (const {url, id} of tabs)
if (url && !url.startsWith(ownRoot) && jobs.push(sendTab(id, data, null, true)) > 20)
await Promise.all(jobs.splice(0));
await Promise.all(jobs);
}

export function broadcastExtension(data, multi) {
return unwrap(browser.runtime.sendMessage({data, multi}));
}
Expand Down
5 changes: 2 additions & 3 deletions src/js/msg.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,8 @@ if (__.ENTRY) {
if (fnOff) port.onDisconnect.addListener(fnOff);
});
}
if (!__.IS_BG) {
const S = chrome.storage;
(S.session || !__.MV3 && (S.local.onChanged ? S.local : S)).onChanged.addListener(onStorage);
if (__.MV3 && !__.IS_BG) {
chrome.storage.session.onChanged.addListener(onStorage);
}

export function _execute(data, sender, multi) {
Expand Down

0 comments on commit eb6d6c4

Please sign in to comment.