问题
I am currently working on a JavaScript project and know that JavaScript source code is accessible through the browser. In the code, I have a variable that stores a secret string that is used by the program. However, I do not want others to view the source code and find out the value of this variable. Is there a way to hide the value of a variable? Or is it possible to change the variable value after? For instance, change the actual source code to set the variable to a different value? This variable is only used the first time an image is loaded so it would be okay to remove it altogether if that is possible.
回答1:
You cannot hide JavaScript content from a programmer. They can always open the developer console and get all your variables.
What's worse, they can use said console to directly bypass any JavaScript validation, so it cannot be your primary security.
If it is something you must hide or secure against, you must look into a server side solution.
回答2:
Javascript is run on the client, so I don't think this is going to possible. Anything that you need to be kept secret is going to need to be server side.
回答3:
JavaScript is client side, and there isn't really anyway to hide the code.
What you can do: Prevent common users from seeing it (aka making it harder to find)
My suggestion is to encrypt the data using some sort of cipher (preferably not an online encryption tool). This stops most lazy people from seeing it.
(Assuming no one is actually trying to find this mysterious value)
回答4:
One work around would be to use Ajax to get the value from another page, like a PHP file.
来源:https://stackoverflow.com/questions/28890783/how-do-i-hide-a-variable-value-in-javascript