2 месяца назад
История
README.md
@dickcocker/wxt-messaging
About
TypeScript module for messaging in web-extension.
Little enhance of browser-messaging.
Supports:
- all browsers;
- manifest versions 2 and 3.
API
Install @types/chrome to get Port type in RuntimePortChatServer.
Classes
-
RuntimePortChatServer - for background.service-worker (background.script);
-
RuntimePortChatClient - for content-scripts;
-
WindowChatP2p - point-to-point chat for content-scripts (main and isolated worlds);
-
WindowChat - chat for content-scripts (main and isolated worlds).
Methods
All chats provides methods:
-
Base:
-
message - to send message;
-
response - to send response to message;
-
on - to add listener of messages or responses;
-
off - to remove listener of messages or responses.
-
-
-
request - to send message and get its response;
-
commands - to set message handlers that can send response.
-
Examples
Base
// content-script
const chat = new WindowChatP2p(true)
chat.on('message', (packet) => {
if (packet.message === 'say hi')
chat.response(packet.id, 'hi')
})
// will:
// 1. get message 'say hi';
// 2. response 'hi'.
// content-script in main world
const chat = new WindowChatP2p(false)
const off = chat.on('response', (packet) => {
console.log('Response: ', packet.data)
off()
})
chat.message('say hi')
// will:
// 1. message 'say hi';
// 2. get response 'hi';
// 3. log it;
// 4. stop listening responses.
Advanced
// service-worker
const chat = new RuntimePortChatServer()
chat.commands({
hi: 'hi',
sum(packet: PacketMessage<number[]>) {
let result = 0
for (const num of packet.data) {
result += num
}
return result
},
promise,
withoutResponse: () => {
// undefined return = no response
}
}, (packet) => console.log('Unhandled message: ', packet.message))
function promise(): Promise<'promise'> {
return new Promise(
resolve => setTimeout(
() => resolve('promise'),
1000
)
)
}
// content-script
const chat = new RuntimePortChatClient('client')
// will log 'hi'
chat.request('hi').then(console.log)
const sum = await chat.request<number>('sum', [1, 2, 3])
// sum is 6
// will log 'promise' in a second
chat.request('promise').then(console.log)
// will never log
chat.request('withoutResponse').then(console.log)
// will log 'something random' in service-worker
chat.message('something random')
Описание
Messaging in web-extension.
Конвейеры
0
успешных
0
с ошибкой