I send the variable newUser
from options.html
to background.html
with chrome.extension.getBackgroundPage()
like this
document.getElementById("save").addEventListener(
"click", function ()
{
var newUser = document.getElementById("getEmail").value;
var bkg = chrome.extension.getBackgroundPage();
bkg.saveNewUser(newUser);
console.log("newUser " + newUser);
} , false)
In background.html
I have
function saveNewUser (newUser)
{
newUser = newUser; //this should be global?
console.log("newUser from options page " + newUser);
}
console.log("newUser from options page " + newUser);
but newUser
is local to the function. My understanding is that if a variable is saved inside a function without the keyword var
it should be global. But in this case it is not. The console.log
outside the function throws Uncaught ReferenceError: newUser is not defined
error.
What am I doing wrong and how can I fix the scope to use newUser
outside the function?
Thanks.
Edit
I tried the following in background.html
but I still get newUser undefined error:
var extension_user
function saveNewUser (newUser)
{
extension_user = newUser; //this should be global
console.log("extension_user from options page " + extension_user);
}
console.log("extension_user from options page " + extension_user);
Update
I changed both pages to reflect the answers and comments but still outside the function the variable is undefined. What am I doing wrong?
options.html
document.getElementById("save").addEventListener(
"click", function ()
{
var newUserEmail = document.getElementById("getEmail").value;
var bkg = chrome.extension.getBackgroundPage();
bkg.saveNewUser(newUserEmail);
console.log("newUserEmail " + newUserEmail);
} , false)
background.html
var newUser
function saveNewUser (newUserEmail)
{
window.newUser = newUserEmail; //this should be global
console.log("newUser from options page inside function" + newUser);
}
console.log("newUser from options page " + newUser);
The
newUser
variable does not exist in the global scope until the functionsaveNewUser
is called. Thus it gives a reference error. Just declare the variablenewUser
in the global scope asvar newUser;
. That should solve the problem. Always use thevar
keyword when declaring variables. It's a good programming practice. Never declare global variables within local scopes. You already know why. Please vote for me if this answer helped you.Edits:
Here's the code to clarify my answer:
If you want to save it as a global variable, you can either change the name of the variable in the function:
or you can use the window scope (which is the same as the global scope):
All global variables are essentially properties of the window object.