I'm developing a chrome extension that uses chrome's runtime sendMessage API to send one time messages back and forth between the extension and the pages the content script is injected into. The problem is that I need some messages to take priority in this system. I've implemented a custom port to do the priority messaging through, however I can't seem to replicate the sendResponse API with the port solution.
The Flow
The client calls a method that returns a promise, which stores a nonce for the request and resolve method, sends a message to its parent via parent.postMessage({data}, '*') and then resolves it when windows message listener is invoked with data containing the same nonce.
The extension's content script listens for messages:
const port = chrome.runtime.connect({name: 'priorityPort'})
function getResponse(data) {
return new Promise((resolve, reject) => {
if (priority) {
port.postMessage({data})
port.onMessage.addListener(msg => {
resolve(msg)
})
} else {
chrome.runtime.sendMessage({data}, resolve)
}
})
}
window.addEventListener('message', async event => {
const response = await getResponse(event.data)
event.source.postMessage({response})
})
and then the background page acts as the other side of the connection
// normal
chrome.runtime.onMessage.addListener((obj, sender, sendResponse: data => {
;(async () => {
sendResponse({ status: 'success', body })
})()
return true
})
// priority
chrome.runtime.onConnect.addListener((port) => {
;(async () => {
port.onMessage.addListener(async msg => {
port.postMessage({ status: 'successs', body })
})
})()
return true
})
However, this doesn't get the response back to the requester as sendResponse does. Any help is greatly appreciated.
sendResponsefunctionality with a long-lived connection - Brandon Deo