I am making a browser game where every 10 seconds, i is incremented, and the points algorithm uses i to determine the number of points awarded. The obvious way (to me) to do this is to use setInterval(10000) for the timer, and run the points calculation inside of the function.
How do I prevent a JavaScript injection that increases i, making the app think that the user has actually been playing for longer than he really has?
I am using Firebase as the back-end. As a PHP programmer, I would normally just do server-side validation of the player's points when he submits them by checking start & end times. I suppose I can do this in Firebase as well, so I probably just answered my own question...
Still, is there a way to just prevent a JavaScript injection? (Prevention, not server-side Detection).
You can make variables essentially private, which means that it will be impossible for the user to change them through plain JS injection. But that won't stop someone from intercepting your Javascript with a debugger, from intercepting your communication between client and server, or from doing all sorts of other fiddling.
To make a variable private, just include it inside a function, execute that function, and return something that includes a function referencing that variable. This is called a closure. It's quite easy to do.
In this fiddle there is a counter variable that is updated every second (not every ten seconds -- I'm in a hurry! :-) ) and another variable, basePoints that together add to the current score.
Publicly exposed is a function that allows you to add to the basePoints value, but nothing allows you to add to the counter. I don't think you can do that without getting inside the JS engine (as a debugger does.) The main point is that there is no way within Javascript to update the counter variable.
var app = this.app = (function() {
var counter = 0;
var basePoints = 0;
var div = document.getElementById("score");
var addPoints = function(nbr) {
basePoints += nbr;
display();
};
document.getElementById("add20").onclick = function() {
addPoints(20);
};
var display = function() {
var points = counter + basePoints;
div.innerHTML = points + " points";
};
setInterval(function() {
counter += 1;
display();
}, 1000);
return {
addPoints: addPoints
};
}());
You can prevent simple manipulation of the variable via things like bookmarklets by just making sure that the variable is internal to a function context and is NOT a global variable and not accessible from the global scope. That can be as simple as putting it into a self executing function context like this:
(function() {
var i;
// code that uses i
setTimeout(function() {
more code that uses i
}, 1000);
})();
In this case, only code inside that first function block can get to the variable i.
Note, as others have said, this doesn't prevent more complicated manipulations that actually change the source javascript before the page executes it or break in the debugger and manipulate things there as there is no way to prevent those, but it does prevent the simplest ways of reaching into a page and changing the variable (like from a bookmarklet).
There is virtually no way to prevent any sort of highscores hacking by calculating the value on the client side and subsequent push to the server side. Only obfuscation and different tricks can make the hacking more or less complicated, but they cannot prevent it at all. That is why server side validation or event better server side calculation is preferred.
Related
We're using blockly to control a phaser game and this is set up so that if statements can be made with custom variables from the game, e.g. the speed or direction of an element within the game.
The problem we've got is that blockly reads the values of those variables when the variables are added onto the if statement (dragged from the toolbox), instead of what they are at runtime, which may have been changed by the physics engine of the game.
For example:
var code = speed;
This returns the value of the speed when the block was added to the code stack from the toolbox. We want it to return the value of the speed when the code is actually running.
We tried creating custom interpreters for them, but it appears that the purpose of those is just for running custom functions, not for returning custom variables.
We tried using a getter function for the variable and returning that in the definition function
Blockly.JavaScript['speed'] = function(block) {
var code = function() {return getSpeed();}
return [code, Blockly.JavaScript.ORDER_NONE];
};
It doesn't fire at all, the statement doesn't evaluate at all... or at least, that's what it seems like
How can we get blockly to read a variable's value at runtime?
If you want to to see individual values of variables or blocks you need to get first all blocks from workspace
Blockly.mainWorkspace.getAllBlocks()
Above code will return all the dropped blocks in workspace from this you can get name of your block using loop and filter the data you want to get
var myblocks = Blockly.mainWorkspace.getAllBlocks()
for( var i=0;i<myblocks.length; i++){
if(myblocks[i].type == 'speed'){
console.log(myblocks[i].getFieldValue('fieldName'));
}
}
In a fairly large application made in Cordova, we keep going back and forth taking a set of variables from the user's LocalStorage. I mean, this set is quite big (in can go from some kbytes to fairly 10mb). I'm pretty sure that keeping variables loaded in memory may not be a pretty good idea (especially in low power, low memory devices), but it turns out that getting them from the LocalStorage looks like it's taking too long. At this moment, our practice is something like this:
function doSomething() {
var ourData = JSON.parse(localStorage.getItem('ourData'));
ourData = processingBackAndForth(ourData);
localStorage.setItem('ourData', JSON.stringify(ourData));
syncWithServer(ourData);
}
Where processingBackAndForth(ourData) is pretty intensive and the whole function is used almost once per 10 seconds. Now, I was thinking, should this be faster?
ourData = JSON.parse(localStorage.getItem('ourData'));
function doSomething() {
ourData = processingBackAndForth(ourData);
localStorage.setItem('ourData', JSON.stringify(ourData));
syncWithServer(ourData);
}
After reading a little on this, well, it basically tells that it's better to keep them in the local scope (which I know is better for encapsulation), but isn't this process a little too much? Just picture it, retrieving from LocalStorage, saving it back again, and letting GC to clean a variable with will be used afterwards once again.
I know one of the points that states the link is that if something needs to be used across the app, and only in really special cases, then make it global, but anyway things like keeping a synced version between the server and LocalStorage still concern a lot to me, so actually I only remove the weight of retriving and garbage collecting.
Would a JavaScript code use a big global variable instead of big local variables to gain some micro-optimizations?
You say that your data can be really large (up to 10MB). Now the question is: would it be better to retrieve your data only one time and save it globally?
In terms of performance, if you get or set your data many times this will really slow down your program, hence your goal is to request and set the data as few times as possible, so that you will not have to wait for the localStorage to retrieve it every time.
Now, given your function:
ourData = JSON.parse(localStorage.getItem('ourData'));
function doSomething() {
ourData = processingBackAndForth(ourData);
localStorage.setItem('ourData', JSON.stringify(ourData));
syncWithServer(ourData);
}
The above code would be the best solution if you call the doSomething() function multiple times, because the data is only retrieved once, then can be elaborated as many times as you want, and saved again. When you have finished using your data you should just delete it (delete ourData;).
Otherwise, if you call the doSomething() function only one time, then the best solution would be to get the data inside the function itself, since that it will only live as long as the function runs, and it will be auto-removed from the memory once the function ends, so the best way to do it would be:
function doSomething() {
var ourData = JSON.parse(localStorage.getItem('ourData'));
ourData = processingBackAndForth(ourData);
localStorage.setItem('ourData', JSON.stringify(ourData));
syncWithServer(ourData);
}
TL;DR you've got two options:
If you use the doSomething() function several times, it's better to save the data globally and then delete it when finished.
If you use the doSomething() function only one time, then it's better to retrieve the data inside the function, using the var keyword.
Due to performance and other issues, I want to split my code into seperate functions as before it was just one big ".ready" function.
I am new to javaScript/jquery but I thought I would give it a go myself. I have done exactly the way I thought it was done but my console is telling me things are undefined so I am guessing I have got things out of scope. I have read up on it in more detail, but still have not got anywhere.
My code works OK at the moment but I want to get into the habbit of clean coding. Can someone point out where I am going wrong so I can carry on myself?
Here is an example of what I have so far
//Global variables
var randomWord = [];
var listOfWords = [];
var populationNumber = [];
var attemptNumber = [];
var completionNumber = [];
var gridSize = [];
generateGrid();
startMusic();
randomizeReward();
//Click event to start the game
$(".start-btn-wrapper").click(function () {
startplay();
});
//Click event to restart the game
$(".restart-btn").click(function () {
restartplay();
});
Thanks
Fiddle: http://jsfiddle.net/QYaGP/
Fiddle with HTML: http://jsfiddle.net/QYaGP/1/
You need to start passing some information into the functions you're defining. If your functions all have no arguments, then you will have to use globally defined variables, hardcoded references to jquery selections etc in order to get anything done.
So as an example, you have a function
function replaySound() {
$("#hintSound").attr('src', listOfWords[randomWord].hintSound);
hintSound.play();
}
This is actually going to play the sound detailed in listOfWords[randomWord] via the element #hintSound. You could do that via:
function playSound(selector, wordlistEntry) {
$(selector).attr('src', wordlistEntry.hintSound);
$(selector)[0].play();
}
And then instead of calling replaySound(), you'd call:
playSound('#hintSound', listOfWords[randomWord]);
This way the behaviour that you want is wrapped up in the function, but the specifics, i.e. the data you need for it, are passed in via the arguments. That allows you to reuse the function to play any sound using any selector, not just #hintSound.
You'll find as you do that that you need to start choosing what a function will act on in the code that calls it, rather than in the function. That's good, because the context of what you're trying to achieve is there in the calling code, not in the function. This is known as 'separation of concerns'; you try to keep logic about a given thing confined to one area, rather than spreading it about in lots of functions. But you still want functions to allow you to encapsulate behaviour. This allows you to change behaviour cleanly and easily, without having to rewrite everything every time some part of the logic changes.
The result should be that you find several functions actually did the same thing, but with different specifics, so you can just have one function instead and reuse it. That is the Don't Repeat Yourself principle, which is also important.
If you are concerned about performance, I would look into using an framework such as AngularJS. You can inject modularized code. Even better, with MVC your view is bound to your model so by changing the model the view automatically updates itself.
Also, stop using class selectors. Use ID selectors. They are much faster. You also want to preload selectors (even with class selectors). That way you are only searching the DOM once:
var ele = $('#elementId');
$(ele).doSomething();
This way, you have a reference to the DOM element. You can use a datastructure to store all of your references outside of the global scope:
var elementReferences = {}; //declaration
elementReferences.mainPage = {}; //use
elementReferences.mainPage.root = $('#mainPage'); //load the root div of a page segment
elementReferences.mainPage.title = $(elementReferences.mainPage.root).children('#title'); //load the title
elementReference.mainPage.form = $(elementReferences.mainPage.root).children('#form'); //load the form
Now you can do this:
$(elementReference.mainPage.form).whatever();
and it doesn't have to search the DOM for the element. This is especially useful for larger apps.
If you put a function within document.ready, as per your fiddle, you are only able to access that function within the scope of the document.ready call. You really want to be able to load/unload functions as needed dynamically within the scope that they are required in, which is where angularjs comes into play.
You also, for the most part, want to remove your functions and variables from the global scope and put them into containers that are sorted by their dependencies and use. This is Object Oriented Programming 101. Instead of having a bunch of arrays sitting within the global scope where they could be overwritten by mistake by another developer, you want to put them within a container:
var arrays = {}; //create the object
arrays.whatever1 = [];
arrays.whatever2 = [];
Obviously, you will probably want a more descriptive name than "arrays". Functions work the same manner:
var ajax = {}; //ajax object
var ajax.get = function(){
};
var ajax.post = function(){
};
var ajax.delete = function(){
};
This generally promotes cleaner code that is more reusable and easier to maintain. You want to spend a good portion of your time writing a spec that fully documents the overall architecture before actually beginning development. NEVER jump the gun if you can help it. Spend time thoroughly researching and planning out the big picture and how everything fits together rather than trying to wing it and figure it out as you go. You spend less time having to reinvent the wheel when you do it this way.
It's developed by google, so it should be around for quite a while. I'm not sure if you are the guy in charge of your system's architecture, but if performance/reusability is an issue at your company it is definitely worth taking a look at. I'd be more than happy to give you a walkthrough regarding most of what I know in terms of software architecture and engineering. Just MSG me if you are interested. Always happy to help!
I have a function with some methods.
function acpwindow(){
this.gui=function(){
//some stuff
}
this.update=function(){
//some stuff
}
}
Now i would like to create multiple instances of that function.
i have a button that create windows. onclick new window will trigger;
function createwindow(){
var object1= new acpwindow();
/*
**Here is a problem I have, How to maintain the objects unique.**
*/
}
When user makes some actions on windows gui those requests sent to server and then server will respond for those request.
Now my other issue is how to how to update particular window according to the response.
The only hope i have is I will generate a unique UUID for each request and the same will return in the response.
I think if you create some kind of window manager to manage the windows you create, it might be easier to send and process requests. Something like:
http://jsfiddle.net/v3T94/1/
And in the example, if it's necessary, you can use the id property. Otherwise, if you keep track of the reference when calling sendRequest, you should be able to perform what you want on the correct acpwindow
The standard way to keep this kind of connection is using closures.
For example if you write
function make_timer()
{
var x = document.createElement("div");
var count = 0;
setInterval(function(){
count += 1;
x.textContent = count;
}, 1000);
return x;
}
every call to make_timer will create an independent DOM node in which the content every second will be incremented. But how can the timer callback remember which is the node that needs to be incremented? The answer is that what is passed to setInterval indeed is not a function but a closure, i.e. a function plus some variables (count and x in this case).
Languages like Java or C++ don't have this concept, but that happens is the the function that is created also it's said to "capture" local variables if they are from an outer scope and it will keep them "alive" even if the outer function that ceated them ends (i.e. when the function make_counter exits).
The very same can be used for ajax requests. What you normally do is just passing the window object to the function that submits the request and a callback closures will be used as completion and error callbacks. The closures will have access to the respective window objects when the answers come back from the server.
Edit
If you really want to use IDs then of course you can... in your example they are store in an array so the array must be traversed to look for the exact ID...
var windowid=$("#guiid").val();
for (var i=0; i<window_manager.windows.length; i++)
if (window_manager.windows[i].id == windowid)
window_manager.windows[i].gui();
Using an object instead of an array would be better because in that case the search could be reduced to a single like:
var windowid=$("#guiid").val();
window_manager.windows[windowid].gui();
Note however that in many cases numeric IDs for are not needed in Javascript because where you would store the window id you could store instead the reference to the window object itself, and for callbacks there is no need of complex machinery for providing context (like it's necessary in C++ or Java) because you have closures.
Not sure if this is considered best practice or if you should even do this but I have a small block of Javascript and I want to know if you can declare a variable, display that variable and then reassign it and display it again? Syntactically this seems correct but I would assume that this is not best practice and should be avoided?
Note: I did not write this block I just want to know if it's ok or if I should change it and use 2 variables code below:
var u1 = 'something';
if (u1.indexOf('Accept') > 0)
{
var URL = 'some URL';
document.writeln(URL);
URL = 'another URL';
document.writeln(URL);
}
Thanks in advance.
EDIT:Thanks for the answers, thought it was a bit daft. :/
Yes you can
You can change variable's value as many times as you need to. Variables are quite often reused so we save memory resources. Not in the way you've used them (because that's an example that would be better off providing constant strings directly when calling functions) but think of an everyday example where we don't even think of multiple variable value assignments. A for loop:
for (var i = 0; i < 100; i++)
{
...
}
In this loop variable i gets assigned a new value 101 times. This is a rather obvious example, where we don't think of this at all, but other than that, we could have a set of loops and reuse the same variable more explicitly and assign it a value lots of times like:
var counter = 0;
for(var item = GetLinkedListFirstItem(); item != null; item = item.Next)
{
counter++;
}
// other code...
counter = 0;
while (counter < 10 || someOtherCondition)
{
// do something else
}
This may be a much better example of explicit variable reusability where its value gets changed lots of times and for different purposes.
Variable naming
Variable reuse is sometimes unwanted/undesired. And that's when we have a meaningful variable name like isUserLoggedIn. It's hard to reuse such variable for other purposes because it would make code unmaintainable.
Variables that are usually reused may hence be iterators (ie. i) or generally named variables without too much meaning. Or variables with more universal name (ie. finished) which can be reused in different contexts that can be associated with such variable name.
Asynchronous code
There are certain situations where you may have problems even though looking at code may seem perfectly fine. And that's when you use async functions which is frequently the case when using Ajax calls or time-deferred calls (ie. setTimeout). Consider the following code:
var loaded = false;
$.ajax({
url: "...",
type: "POST",
success: function(){
loaded = true;
}
});
if (loaded === true)
{
// do something important
}
// ok loaded not used any more, so we can reuse it
// we can easily change its type from number to string or anything else
loaded = "Peter loaded his gun";
This code has a bug, because important code won't be executed. Ever! This is quite a frequent misconception by unsavvy developers not understanding asynchronism.
Hint: When code issues an Ajax call it doesn't wait for a response but rather continues execution and executes if statement. Even though Ajax call would respond in 0time ticks, success function wouldn't execute until this currently running code wouldn't finish execution. That's how Javascript works. Queued code execution. In the end when Ajax async code would execute it would eventually overwrite the string that was stored in the variable.
Why not? Of course, it's normal to change variable value as much times as you want. That's actually reason why it's called "variable", not "constant" :)
I'd say it's perfectly fine to do so.
However, keep in mind that it can cause problems with asynchronous code. Take the following example for instance, where async accepts a callback that runs some time later:
var a = 123;
async(function() {
alert(a); // alerts 456, because `a` was set to 456
// *before* this callback was run.
// Because there is only one `a`, that variable
// has been overridden
});
a = 456;
async(function() {
alert(a); // alerts 456
});
Yes it is possible, and in this case there is no point in creating a new variable. However, if you have a lot of code reassigning a variable later could definitely be confusing especially if at first it's an object then later it is a string.
Variables can be reassigned in JavaScript. Whether they should or not is a question of style and context.
I normally prefer to re-use variables rather than create new ones