Move lib/Messenger to messaging module

This commit is contained in:
hensm
2021-05-04 12:20:59 +01:00
parent 453274307f
commit e6ddd43496
2 changed files with 30 additions and 38 deletions

View File

@@ -1,36 +0,0 @@
"use strict";
import { TypedPort } from "./TypedPort";
interface RuntimeConnectInfo {
name: string;
}
interface TabConnectInfo {
name: string;
frameId: number;
}
export default class Messenger<T> {
connect(connectInfo: RuntimeConnectInfo) {
return browser.runtime.connect(connectInfo) as
unknown as TypedPort<T>;
}
connectTab(tabId: number, connectInfo: TabConnectInfo) {
return browser.tabs.connect(tabId, connectInfo) as
unknown as TypedPort<T>;
}
onConnect = {
addListener(cb: (port: TypedPort<T>) => void) {
browser.runtime.onConnect.addListener(cb as any);
}
, removeListener(cb: (port: TypedPort<T>) => void) {
browser.runtime.onConnect.removeListener(cb as any);
}
, hasListener(cb: (port: TypedPort<T>) => void) {
return browser.runtime.onConnect.hasListener(cb as any);
}
}
}

View File

@@ -1,7 +1,5 @@
"use strict";
import Messenger from "./lib/Messenger";
import { TypedPort } from "./lib/TypedPort";
import { BridgeInfo } from "./lib/bridge";
@@ -180,4 +178,34 @@ export type Port = TypedPort<Message>;
export type Message = NarrowedMessage<Messages[keyof Messages]>;
/**
* Typed WebExtension-style messaging utility class.
*/
class Messenger<T> {
connect(connectInfo: { name: string; }) {
return browser.runtime.connect(connectInfo) as
unknown as TypedPort<T>;
}
connectTab(tabId: number
, connectInfo: { name: string
, frameId: number }) {
return browser.tabs.connect(tabId, connectInfo) as
unknown as TypedPort<T>;
}
onConnect = {
addListener(cb: (port: TypedPort<T>) => void) {
browser.runtime.onConnect.addListener(cb as any);
}
, removeListener(cb: (port: TypedPort<T>) => void) {
browser.runtime.onConnect.removeListener(cb as any);
}
, hasListener(cb: (port: TypedPort<T>) => void) {
return browser.runtime.onConnect.hasListener(cb as any);
}
}
}
export default new Messenger<Message>();