Google chrome extension 未定义使用sendMessage从内容脚本到后台页面的Google Chrome扩展变量

Google chrome extension 未定义使用sendMessage从内容脚本到后台页面的Google Chrome扩展变量,google-chrome-extension,local-storage,Google Chrome Extension,Local Storage,我正在开发一个基本的Google Chrome扩展,但从localStorage获取值时遇到了问题。我在内容脚本中使用sendMessage从后台页面请求变量。当我得到响应时,变量总是“未定义的”,除非我在响应后加上类似于alert()的东西……然后变量包含我的值。你能帮我弄清楚为什么会这样以及如何正确地做吗?我已经为这篇文章做了代码,它在下面。多谢各位 manifest.json background.js 非常感谢您的帮助!:) 因为响应在回调函数中。当你有这个: chrome.ext

我正在开发一个基本的Google Chrome扩展,但从localStorage获取值时遇到了问题。我在内容脚本中使用sendMessage从后台页面请求变量。当我得到响应时,变量总是“未定义的”,除非我在响应后加上类似于alert()的东西……然后变量包含我的值。你能帮我弄清楚为什么会这样以及如何正确地做吗?我已经为这篇文章做了代码,它在下面。多谢各位


manifest.json
background.js

非常感谢您的帮助!:)

因为响应在回调函数中。当你有这个:

chrome.extension.sendMessage({greeting:"color"},function(response){color = response.farewell;});

alert('content - ' + color);

浏览器执行sendMessage,然后立即转到下一行,即警报。sendMessage中的回调在之后启动。警报“修复”了它,因为您基本上暂停了浏览器。如果要使用颜色作为变量,则只能在callback:function(response)中使用它。

查看此答案以了解代码的错误以及解决方法:这很有意义。谢谢你,雷蒙德和罗伯。
alert('content');

var color;

chrome.extension.sendMessage({greeting:"color"},function(response){color = response.farewell;});

// alert('pause'); // uncommenting this line lets me get the value...why?

alert('content - ' + color);
alert('background');

localStorage["color"] = "lightblue";

var color = localStorage["color"];

alert('background - ' + color);

chrome.extension.onMessage.addListener(function(request,sender,sendResponse)
{

if (request.greeting == "color") {sendResponse({farewell:color});}

});
chrome.extension.sendMessage({greeting:"color"},function(response){color = response.farewell;});

alert('content - ' + color);