开发者

How to synchronized messaging between background and contentscript?

开发者 https://www.devze.com 2023-02-13 17:17 出处:网络
I currently have an issue with the communication bewteen my background and my contentscript. The problem is that they can communicate but it seems to be asynchronous.

I currently have an issue with the communication bewteen my background and my contentscript. The problem is that they can communicate but it seems to be asynchronous.

Let me show you my code.

yourToolbar.js

chrome.extension.sendRequest({getStatut : "none"}, function(response) 
{
    console.log('yourToolbar : ' + response.statut);
    localStorage['activated'] = response.statut;
});

if (localStorage['activated'] == "show") 
{
        // injection
}

background.js

chrome.extension.onRequest.addListener(function(request, sender, sendResponse) 
{   
    if(request.getStatut)
    {
        console.log('Background : ' + localStorage['activated']);
        sendResponse({statut : localStorage['activated']});
    }
    else if(request.modifyToolbar)
{
    if (request.modifyToolbar == "hideToolbar") 
    {
        localStorage['activated'] = "hide";
    }       
}
});

The real problem is that when i hide the toolbar, the toolbar only disapear after 1 more refresh.开发者_运维技巧 So it's seems that the communication is not up to date... When i print on the console the value of "activated" it show me the good value, but apparently the condition on yourtoolbar.js test the previous value of "activated"

Someone have an idea ?

EDIT : One strange thinks, is that if i add an alert just before the condition it work perfectly...

alert(ocalStorage['activated']);
        if (ocalStorage['activated']== "show") 
        {


All messaging in Chrome and all(?) API methods are asynchronous.

So your toolbar.js should look like:

chrome.extension.sendRequest({getStatut : "none"}, function(response) 
{
    console.log('yourToolbar : ' + response.statut);
    localStorage['activated'] = response.statut;

    //inside a callback
    if (localStorage['activated'] == "show") 
    {
            // injection
    } 
});
0

精彩评论

暂无评论...
验证码 换一张
取 消