Note that there are some explanatory texts on larger screens.

plurals
  1. POGoogle Chrome Extension Variable using sendMessage from Content Script to Background Page is Undefined
    primarykey
    data
    text
    <p>I have a basic Google Chrome Extension I am working on, and having a problem getting a value from localStorage. I am using sendMessage in the content script to ask for the variable from the background page. When I get the response, the variable is always "undefined", unless I put something like an alert() after the response...then the variable contains my value. Can you help me to figure out why this is and how to do it correctly? I have made the code for this post and it is below. Thank you very much!</p> <hr> <h2>manifest.json</h2> <pre><code>{ "name": "Test Extension", "version": "1.0", "manifest_version": 2, "description": "A test extension.", "background": { "scripts": ["background.js"] }, "content_scripts": [ { "matches": ["&lt;all_urls&gt;"], "js": ["content.js"] } ], "permissions": [ "tabs", "&lt;all_urls&gt;" ] } </code></pre> <hr> <h2>content.js</h2> <pre><code>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); </code></pre> <hr> <h2>background.js</h2> <pre><code>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});} }); </code></pre> <hr> <p>Thank you very much for any help! :)</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload