chrome.runtime.onMessage.addListener does not wait for response

Viewed 32

I'm making an extension where if a content script sends a message, a background script will display a notification with 2 buttons.

The button choice should be sent back to the content script, but it doesn't work. The docs say if you return true, it will wait for the response but it doesn't. I've seen multiple questions on this, but none of the answers worked.

bg.js

chrome.runtime.onMessage.addListener(
    function(req, sender, resp) { // Tried async too

        // Make sure we get the URL of the tab that sent the message
        chrome.tabs.get(sender.tab.id, function(tab) {

            chrome.notifications.create({
                type: 'basic',
                title: 'hi',
                message: 'you are on ' + new URL(tab.url).hostname,
                iconUrl: 'icon.png',
                buttons: [
                    { title: 'Allow' },
                    { title: 'Block' }
                ]
            }, function(id) {

                chrome.notifications.onButtonClicked.addListener(function(_, _id) {

                    // Respond if we sent the notification
                    if (_id === id) resp({ rejected: !id, id }) // Never gets sent

                })

            })
        })

        return true // does not make it wait for resp()
    }
)

content.js

chrome.runtime.sendMessage('a message', function(response) {
    console.log(response) // Nothing ever gets logged
})

Please help.

0 Answers
Related