The problem here is that the chrome runtime is running asynchronously. So when you execute that first function, it won't log those 1 and 2 messages until after the response is sent. It registers the callback and proceeds with the rest of the script. Since it takes a little bit of time for the runtime to respond, even though it may be fast, it won't receive a message back until after it's already logged 3 to the console.
javascript function running out of order
-
07-10-2022 - |
質問
In a Chrome Extension, I am trying to get saved information from the option page and use it in a content script. I am passing a message to the background script to get it. I have surrounded the sendMessage in the content script in a temporary function(I think that's what it's called) so that I could store the color outside of it. Unfortunatly it leads to things running about out of order. The output from the code below is:
3red
1red
2blue
I assume this has something to deal with the fact that I have created a temporary function.
Content_script.js:
(function(){
chrome.runtime.sendMessage({method: "getLocalStorage", key: "favColor"},
function(response) {
console.log("1"+color);
color = response.data;
console.log("2"+color);
}
)
})(color);
console.log("3"+color);
a.style.backgroundColor = color;
Background.js:
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.method == "getLocalStorage")
sendResponse({data: localStorage[request.key]});
else
sendResponse({}); // snub them.
});
解決
所属していません StackOverflow