V
V
Vitaly2018-03-06 11:41:22
Google
Vitaly, 2018-03-06 11:41:22

How to correctly send messages from background.js to content_script in a Chrome extension?

All good!
I'm writing extensions for Chrome and ran into a problem that I don't understand when sending a message with background to content_script . I receive data in background via Websocket and send it to content_script .
Here is my code:
background:

ws.onmessage = function (event) {
        console.log('MESSAGE: ' + event.data);
        let msg = event.data;
        console.log('got msg form device -> ', msg);
        chrome.tabs.query({active: true}, function (tabs) {
            console.log('tab > ', tabs[0].url, tabs[0].id);
            let convertedData = String(tabs[0].url).includes("siteA.com") ? dataFormater('siteA', msg) : dataFormater('siteB', msg);
            chrome.tabs.sendMessage(tabs[0].id, {
                action: msg == 'removed' ? msg : 'showDepositModal',
                data: convertedData
            }, function (response) {
                console.log(response);
            });
        })
    };

And content_script :
chrome.runtime.onMessage.addListener(
    function (request, sender, sendResponse) {
        if(window.location.href.includes("siteA.com") || window.location.href.includes("siteB.com")){
            if (request.action == 'showDepositModal') {
                console.log("content script got masg ", request.data);
                showModal(request.data);


            } else {
                hideModal();
            }
        }


    }
);

It seems like everything works, but not very stable :(
Very often content_script does not receive messages from background , in order for everything to work again, you just need to refresh the current page, and everything works ... until some time. I don’t understand why ....
An interesting fact is that if you turn on the developer mode in the extensions and open background.js , I didn’t observe such “stickiness.”
I would be grateful for your help in solving this incomprehensible situation for me

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robot Chappie, 2018-03-06
@Scorpiored88

Add the permission to the manifest.json file "permissions" : [ "activeTab" ].
and

"background" : { "scripts" : [ "eventPage.js" ], "persistent" : true }

namely"persistent" : true

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question