From cad3afadc26577ed1afeccdc3cd3812ef481201e Mon Sep 17 00:00:00 2001 From: glacambre Date: Tue, 2 Oct 2018 12:38:30 +0200 Subject: [PATCH] messaging.ts: Implement messageOwnTab function messageOwnTab does exactly what the name suggests. In a lot of cases, it can and should replace messageActiveTab when it is called from the content/commandline_frame script. --- src/messaging.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/messaging.ts b/src/messaging.ts index 75b0c8d7..1d2b3664 100644 --- a/src/messaging.ts +++ b/src/messaging.ts @@ -7,6 +7,7 @@ export type TabMessageType = | "commandline_content" | "commandline_frame" export type NonTabMessageType = + | "tabid_background" | "commandline_background" | "controller_background" | "browser_proxy_background" @@ -83,6 +84,18 @@ export async function messageTab(tabId, type: TabMessageType, command, args?) { return browserBg.tabs.sendMessage(tabId, message) } +let ownTabId = undefined +export async function messageOwnTab(type: TabMessageType, command, args?) { + if (ownTabId === undefined) { + ownTabId = await browser.runtime.sendMessage({ + type: "tabid_background", + }) + } + if (ownTabId === undefined) + throw new Error("Can't message own tab: ownTabId is undefined") + return messageTab(ownTabId, type, command, args) +} + export async function messageAllTabs( type: TabMessageType, command: string, @@ -112,6 +125,12 @@ export function addListener(type: MessageType, callback: listener) { } } +addListener("tabid_background", (message, sender, sendResponse) => { + sendResponse( + sender.tab ? sender.tab.id : new Error("Message sender not in a tab"), + ) +}) + /** Recv a message from runtime.onMessage and send to all listeners */ function onMessage(message, sender, sendResponse) { if (listeners.get(message.type)) {