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.
This commit is contained in:
glacambre 2018-10-02 12:38:30 +02:00
parent dc064d322f
commit cad3afadc2
No known key found for this signature in database
GPG key ID: B9625DB1767553AC

View file

@ -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)) {