I have an application that has inside the local storage a variable named token.
I want to write a code that clears the console and the shows an alert(); with
the aforementioned variable.
This is what I have managed to do so far
clear(); if(localStorage){alert(localStorage.getItem("token"));}
But I keep getting the error that localStorage is not defined. More precisely:
Uncaught ReferenceError: localStorage is not defined
at <anonymous>:1:12
Any ideas?
I don't have the full context of your code, but if localStorage isn't defined then you can't check if it's value is defined.
For example, and that's true for any variable, if you don't define the variable bla, then the following code will throw the same error:
if (bla) console.log(bla);
You should use if (typeof localStorage !== "undefined") instead.
Furthermore, your browser doesn't necessarily support localStorage, so you should check that before. And using try-catch is also a good idea when working with localStorage.
In some cases, you cannot use "localStorage" as a boolean.
As Gilad Bar suggested, use if (typeof localStorage !== "undefined") instead.
Also, make sure that "token" isn't null or undefined.
Related
I searched everywhere to find the solution, but I find none of them are relevant to mine.
I tried to store a variable in local storage, but I'm getting the below error:
raise MakeError('TypeError',
JsException: TypeError: Undefined and null dont have properties (tried getting property 'setItem')
So I checked whether it is running on browser,
if (typeof window !== 'undefined') {
console.log('You are on the browser')
if(message1!='undefined'){
console.log("message1 is not undefined")
window.localStorage.setItem("vOneLocalStorage",message1);
}
}
Before giving the error, it printed "You are in the browser" in console, which I gave in the code to test
output in console before giving the error
I don't understand what is the cause, and why is it not able to store the variable in the local storage.
The tech stack I use are Javascript, React, python, and Js2py library to pass input from Python to Javascript.
This question already has answers here:
How to check a not-defined variable in JavaScript
(15 answers)
Closed 3 years ago.
So I'm trying to swap between API links in my angular app based on the origin, but it is an SSR app so I'm trying to account for an environment variable as well as window location, the code is as follows:
const getApiUrl = (): string => {
if (process && process.env?.AZURE_ENV === 'development') {
return 'devlink for SSR';
} else if (
window &&
window.location.origin === 'devclient'
) {
return 'devlink for frontendclient';
} else {
return 'link.com/';
}
};
Now the error being thrown out is:
Uncaught ReferenceError: process is not defined
I've digged into the 'compiled' script and have 100% confirmed it's coming from this piece of code.
Shouldn't this still work though?
I've also tried a vesion where I just have if(process) and get the exact same result as above.
Probably it is not there so it will fail to evaluate, maybe testing it like typeof process !== 'undefined' will help
If process has never been defined in any accessible context I think it will fail with an UncaughtReferenceError because it is trying to access something not in the context. Undefined means that the variable exists but it has no value set and this error says that the variable is just not there, thats why checkinng the type of it will probably solve the issue.
Nope. While a non-exising field of an object is really undefined, read access to a non-existing variable is an error in JavaScript, use typeof as other answers suggest...
console.log("typeof {}.process",typeof {}.process);
console.log("typeof process",typeof process);
console.log("{}.process",{}.process);
console.log("process",process);
... also, your code is TypeScript, the :string part gives it away. Which means it is compiled to strict mode, and even write access to a non-existing non-local variable would be an error.
I'm not very familiar with angular. But typically this is supposed to be client side code and it doesn't have access to node environment variables. Even if it is SSR.
If you are using webpack you could define the environment variable as a global variable on the client side:
https://webpack.js.org/plugins/define-plugin/
For your case if you don't want to use any other solutions, firstly check global , its like window but on node, so process will be stored in global.process
I am running into an issue in my Angular 2 app where I'm getting an undefined error that's not making sense to me. What's more perplexing is that, after getting the undefined error, I can effectively check the exact same value in the console and get it with no issues.
First off, here's a version of the function that DOES work:
public getApplicableResult()
{
if (!this.customer || !this.customer.services || !this.customer.services.getAt(0))
{
console.log('Services not available...');
return;
}
else if (this.customer && this.customer.services && this.customer.services.getAt(0))
{
console.log(this.customer.services.getAt(0));
}
When I run this function I get this in the console for my "console.dir" of my object literal:
CustomerServiceDetails
assignments:(...)
authorizations:(...)
If I then click on "assignments" in the console, I get this expanded result:
assignments:
CustomerAssignmentCollection
count:1
items:Array(1)
So all the data is seemingly there and available.
However, if, in my function, if I were to try and access these nested values more directly - such as the value for "count" above, I get an undefined error. That's what I'm not understanding. Perhaps it's something I misunderstand about how the console works. But if seems to me that if I can access the value for this property in the console, then I should be able to access it directly via my function.
Here's an example of the same function, slightly altered to get the result for "count" within assignments, that returns undefined:
public getApplicableResult()
{
if (!this.customer || !this.customer.services || !this.customer.services.getAt(0).assignments)
{
console.log('Services not available...');
return;
}
else if (this.customer && this.customer.services && this.customer.services.getAt(0).assignments)
{
console.dir(this.customer.services.getAt(0).assignments.count);
}
The specific error I get is:
Cannot read property 'assignments' of undefined;
To add some additional info, assignments is not an array, it's a collection.
Two questions here:
1.) Why isn't my first "if" clause handling the 'undefined' error? How could I adjust it to handle the situation better?
2.) Why can I call the first function, get a result, and then drill down from there in the console to get what I need, but if I try and access a more nested part of the object in the function itself, I get undefined as a result?
One additional detail, I was calling this via Angular's ngAfterViewChecked(). So what that should do, even if it's a timing issue, is return the first "if" else clause result until the value is available, and then it should show the result - i.e., it should execute the "else if" block - because AfterViewChecked() keeps checking. But this isn't happening. I'm just getting the undefined result I mentioned above.
You have a json object.
By mistake you pass some element (property1) to a function and the value passed doesn't exists...
myFunction (json.propety1); // it must be 'property1' , with r
I'd like to set any configure element to say the browser "I can't pass undefined json properties, rise an error"
I think this is not possible, is't it ?
Thanks in advance
in myfunction you can check for undefined and then do something
like
function myFunction(jsonproperty){
if(jsonproperty === undefined){
//do something with the DOM to pass whatever you wanna say in the browser
}
}
Is that what you were trying to do? You could also throw an exception like this:
throw "json property was undefined"
but you would only see that in some kind of js debugger console. Nowadays all browser have one. Usually accessible with "F12"
I have been trying to figure out this particular problem in my developer tools, but I've had no luck thus far. I have an error on one of my js files that says
Uncaught TypeError: Cannot read property 'value' of null
The following error refers to the 1st variable of dt_version below. The particular thing is if I comment out the first line of code. I get the same error on the following variables of offload1 and offload2. The variable is a number that I am trying to get passed over. I run this function on my body when the page loads...onload=updatetotal();
function updatetotal() {
var dt_version = document.getElementById("dt_version").value-0;
var offload1 = document.getElementById("capacity_offload1").value-0;
var offload2 = document.getElementById("capacity_offload2").value-0;
var offload3 = document.getElementById("capacity_offload3").value-0;
}
If a run an if statement looking for document.getElementByID("dt_version");...it defaults to false..so its not being carried over though on the previous page, I can see its input fine with the value in it. What am I missing here guys?
This error means that the id dt_version does not exist. Check your html to make sure it is there:
var dt = document.getElementById("dt_version");
if (dt){
// do your stuff
}else {
console.log("dt does not exist")
}
Another cause for this error may be- as you are calling the javascript function on page load there is a possible chance that your control is not yet completely rendered to the page. A simple solution is just move that control to the beginning of the page. If it doesn't work then an reliable solution is, call the function inside jquery $(document).ready().