Получилось)
Схема такая:
//manifect.json
{
"name": "test",
"description": "test",
"version": "0.1",
"permissions": [
"management",
"<all_urls>"
],
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["content.js"],
"run_at": "document_end"
}],
"background": {
"scripts": ["background.js"]
},
"manifest_version": 2
}
//content.js
const script = document.createElement('script')
script.textContent = `${sendMessageToExtension}`
document.documentElement.appendChild(script)
document.addEventListener('pageMessage', ev => {
chrome.runtime.sendMessage(ev.detail, sendResponse)
})
function sendResponse(response) {
const event = new CustomEvent(response._id, { detail: response })
document.dispatchEvent(event)
}
function sendMessageToExtension(extensionId, message) {
return new Promise((resolve, reject) => {
const _id = Math.random().toString()
const event = new CustomEvent('pageMessage', {
detail: {
_id,
message,
extensionId
}
})
const responseHandler = (event) => {
resolve(event.detail.message)
document.removeEventListener(_id, responseHandler)
}
document.addEventListener(_id, responseHandler)
document.dispatchEvent(event)
})
}
//background.js
chrome.management.getSelf(extension => {
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.extensionId !== extension.id) return
// наше сообщение
const message = request.message
// готовим ответ
const response = { result: message.value * 2 }
sendResponse(Object.assign({}, request, { message: response }))
})
})
теперь на каждой странице появляется функция sendMessageToExtension
// web page
main()
async function main() {
const extensionId = 'adifgidpakahghppcfdelejcfgnpdenj'
const response = await sendMessageToExtension(extensionId, { value: 5 })
console.log(response.result) // 10
}