FoxRefire
FoxRefire

Reputation: 1

Get multiple response as Promise Array when sending message with chrome.tabs.sendMessage

When all_frames: true is set in manifest.json, the content script runs on all frames of the target page, but when a message is sent to the content script from another script, I would like to know how to get the response of all frames as Promise array like [Promise(Response of frame1), Promise(Response of frame2)...].

The extension and test page I created for this question can be found on my Github.

If anyone knows of a better way to do this, I would be grateful if anyone could let me know.

Thanks.

Upvotes: 0

Views: 60

Answers (1)

FoxRefire
FoxRefire

Reputation: 1

Self-resolved

chrome.tabs.query({active:true, currentWindow:true}, async tabs => {
    let promises = await sendMessagePromises(tabs[0].id)
    console.log(promises)
})

async function sendMessagePromises(tabId){
    let promises = []
    let frames = await chrome.webNavigation.getAllFrames({tabId:tabId})
    frames.forEach(f => {
        let promise = chrome.tabs.sendMessage(tabId, {type:'ping'}, {frameId:f.frameId})
        promises.push(promise)
    })
    return promises
}

screenshot

Upvotes: 0

Related Questions