如何同步后台和内容脚本之间的消息传递?
目前,我的背景和内容脚本之间的沟通存在问题。问题是它们可以通信,但似乎是异步的。
让我向你展示我的代码。
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";
}
}
});
真正的问题是,当我隐藏工具栏时,工具栏只会在再刷新 1 次后才会消失。所以看来通信不是最新的...当我在控制台上打印“已激活”的值时,它向我显示了良好的值,但显然 yourtoolbar.js 上的条件测试了“已激活”的先前
值有主意吗?
编辑:一个奇怪的想法是,如果我在条件之前添加一个警报,它就会完美地工作......
alert(ocalStorage['activated']);
if (ocalStorage['activated']== "show")
{
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")
{
Chrome 中的所有消息传递和所有(?)API 方法都是异步的。
所以你的toolbar.js应该是这样的:
All messaging in Chrome and all(?) API methods are asynchronous.
So your toolbar.js should look like: