How to make javascript game not editable/hackable - javascript

Im making a game with javascript for my website, but its easy to hack or do sql infections on it, you can also just inspect the code and change the values of any variable in the script, how can i make the script and code not viewable and editable?
Here`s my code
<script>
var scoreNumber = 0;
document.getElementById('scoreLabel').value = scoreNumber;
document.getElementById("scoreLabel").innerHTML = scoreNumber;
</script>
<html>
<style>
body{
background-image: url('snow.gif');
background-size: cover;
}
</style>
<head>
<center>
<h1 id="bottom">Cilus Networks</h1>
// Anyone can change the scrollamount, which i dont want
<marquee scrollamount="20"
direction="right"
behavior="scroll">
<img id="one" src="santa.png" height="150" width="150">
</marquee>
<marquee scrollamount="20"
direction="left"
behavior="scroll">
<img id="two" src="santa.png" height="150" width="150"> <source src="plimp.mp3" type="audio/mp3">
</marquee>
</center>
<h1 id="scoreLabel">0</h1>
</head>
<body>
</body>
<script>
var powerup;
var lifes;
//Anyone can change this, which i also dont want.
powerup = 0;
if (powerup == 2 ) {
function add(){
scoreNumber = scoreNumber +1000
document.getElementById('scoreLabel').value = scoreNumber;
document.getElementById("scoreLabel").innerHTML = scoreNumber;
}
};
if (powerup == 5 ) {
function add(){
scoreNumber = scoreNumber +500
document.getElementById('scoreLabel').value = scoreNumber;
document.getElementById("scoreLabel").innerHTML = scoreNumber;
}
};
function add(){
scoreNumber = scoreNumber +1
document.getElementById('scoreLabel').value = scoreNumber;
document.getElementById("scoreLabel").innerHTML = scoreNumber;
setInterval(function(){ window.location.replace("http://cilusnetworks.com/thankyouMDT.php"); }, 400);}
</script>
Any ideas on how to do this? I have done som research but i cant seem to find anything..

Anything you send to the client is merely a suggestion of what you think would be a good idea for the client to do. The client is perfectly free to ignore your suggestions and do its own thing: show your code to the user instead of executing it, add 12 to every variable when it's defined, make demons fly out of your nose, whatever. If you really want to rule with an iron fist, you'll have to keep the logic of your game tightly under your control: all the game code lives on your server, never to be sent out, and you tell the client "this is what happens, what do you want to do?" And then make sure the response makes sense and is legal.
If you don't want to go that far, the best you can do is obfuscation, making it more difficult for the user to figure out what a valid change to your suggestion would be.

You might be able to do an <iframe></iframe> with the html file containing the game stuff on a different html file.
For example: <iframe src=“game.html”></iframe>

Related

javascript how to make all strings italic after hyphen?

Good morning to all
I have a question related to my big commerce products title. here I need the first part of the product's title in bold and after the hyphen or dash the second part need in italic. But problem is that the products title comes with one global variable %%GLOBAL_ProductName%% which I cannot make separated with the span tag. so can you suggest me how I can achieve the rest of strings after hyphen show in Italics with the help of javascript?
For example, check this screenshot https://www.screencast.com/t/fKy0FhByzzl
and here is big commerce website http://rp-staging2.mybigcommerce.com/categories
<li class="%%GLOBAL_AlternateClass%%">
<div class="ProductImage" data-product="%%GLOBAL_ProductId%%">
%%GLOBAL_ProductThumb%%
</div>
<div class="OutOfStockMessage InfoMessage" style="%%GLOBAL_ItemSoldOut%%">
%%SNIPPET_SideAddItemSoldOut%%
</div>
<div class="ProductActionAdd" onclick="location.href='%%GLOBAL_ProductLink%%';">
<p>%%GLOBAL_ProductName%%
</p>
<p><em class="p-price">%%GLOBAL_ProductPrice%% USD</em>
</p>
%%GLOBAL_ProductAddText%%
</div>
</li>
%%GLOBAL_ProductName%%
this variable showing products name please check screenshot and website i have provided link
Using some of the cool es6 features (array destructuring and template literals)
$(".pname").each(function () {
[beforeDash, afterDash] = $(this).text().split(" - ");
$(this).html(`${beforeDash} - <i>${afterDash}</i>`);
});
Looks like:
And if you are using jQuery in your website, you can use something like this:
$( window ).on( "load", function(){
var text = $('.text');
var x = text.text().split('-');
text.html(`${x[0]} - <i>${x[1]}<i>`);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">
Hello - World
</div>
When ever possible do this kind of split at the server side. Because client side you will manipulate strings after loading the page. So it is not good to do at client side. But anyhow I have written jquery code to fulfill your requirement. I have written in a click event for demo purpose. Please do the logic on onload event.
$("#btn").click(function(){
$(".productName").each(function(){
var title = $(this).text();
var firstSentence = "<b>"+title.substr(0,title.indexOf('-'))+"</b>";
var secondSentence = "<i>"+title.substr(title.indexOf('-')+1)+"</i>";
var finalTitle = firstSentence+ "-" + secondSentence;
$(this).html(finalTitle);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<a class="productName"> Sample1 - Product Name1</a><br>
<a class="productName"> Sample2 - Product Name2</a><br>
<input id="btn" type="button" value="Change Format">
</body>
</html>
Check this if it helps...
https://jsfiddle.net/Lz8p11mc/1/
You need to split your product name with '-' and then add these isolated names in separate spans and then you can style these spans as you want. I have written code for simple test case , you can modify it as per your requirement.
<html>
<script>
var productName = 'ABC-XYZ';
var separatedNames = productName.split('-');
var firtsName = separatedNames[0];
var secondname = separatedNames[1];
window.onload = function() {
//when the document is finished loading, replace everything
//between the <a ...> </a> tags with the value of splitText
document.getElementById("myTag").innerHTML = '<span>'+firtsName+'</span>-<span class="secondnameCls">'+secondname+'</span>';
}
</script>
<body>
<li class="%%GLOBAL_AlternateClass%%">
<p><a id='myTag'></a></p>
</li>
</body>
</html>

HTML/CSS - How to set text (e.g. 'Quote of the Day') to change automatically on page load/reload?

I am quite new to HTML/CSS. I've got a fairly basic website going in which I have a funny quote under my title. My friend asked me if it changes every time the page loads and that gave me the idea to do something like that. I was wondering if there was any way to manage this in HTML/CSS. I do know some Javascript, so I can also do it on that if needed.
Do I need a list of quotes saved in a file? Can they be pulled from a website/online list? What is the most efficient way to do this?
Thanks
There is a free Quote and Expression API called Forismatic which retrieves a random inspiring quote or expressions. See here for an example quote.
I created an example Codepen of this API using JQuery with AJAX and Bootstrap:
<script>
$(function() {
var quote = $('.quote-text');
getQuote(quote);
$('#getQuote').click(function(event) {
event.preventDefault();
getQuote(quote);
});
});
function getQuote(quote) {
var url = 'http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=jsonp&jsonp=?';
$.getJSON(url, function(data) {
quote.html(data.quoteText);
});
}
</script>
<div class="jumbotron text-center">
<p class="quote-text"></p>
<button id="getQuote" class="btn">Get Quote</button>
</div>
You can see the codepen here - http://codepen.io/jamesg1/pen/zKORbk
You can use Math.random() to get your randomized index. Math.random() generates a value from 0 (inclusive) to 1 (exclusive).
The onload will be called each time the page is loaded.
<!DOCTYPE html>
<html>
<body onload="randomQuotes()">
<h1>Hello World!</h1>
<p id="quote"></p>
<script>
var quotes = ['hi', 'bye', 'lol', 'hello', 'world']
function randomQuotes() {
var idx = Math.floor(Math.random() * quotes.length)
document.getElementById('quote').innerHTML = quotes[idx]
}
</script>
</body>

making and appending a substring from getElementById

I am trying to make a news preview from a separate file (text.html) I want to be able to just display the first 100 characters of a div (id="news"). I don't want to use Ajax or Php. Here is my code, not sure how to make it work, thanks guys.
<body onload="home()">
<div id="content"></div>
<script>
function home() {
var x = document.getElementById("content").innerHTML = '<object width="100%" height="100%" type="text/html" data="text.html"></object>';
var pre = x.substring(0,5);
alert(pre);
}
</script>
</body>

How to make contenteditable save permanently and globally?

I am trying to create a page which is very similar to Goodle-Docs, where everybody with access to the page will simply be able to edit the text. However my problem is that I can only get these changes to save locally, how do I make users edit the content-editable text so that the change is visible on all devices?
I am using this tutorial, http://www.developerdrive.com/2012/06/allowing-users-to-edit-text-content-with-html5/ but the changes of the page are only saved locally.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function saveEdits() {
//get the editable element
var editElem = document.getElementById("edit");
//get the edited element content
var userVersion = editElem.innerHTML;
//save the content to local storage
localStorage.userEdits = userVersion;
//write a confirmation to the user
document.getElementById("update").innerHTML="Edits saved!";
}
function checkEdits() {
//find out if the user has previously saved edits
if(localStorage.userEdits!=null)
document.getElementById("edit").innerHTML = localStorage.userEdits;
}
</script>
</head>
<body onload="checkEdits()">
<div id="edit" contenteditable="true">
Here is the element
</div>
<input type="button" value="save my edits" onclick="saveEdits()"/>
<div id="update"> - Edit the text and click to save for next time</div>
</body>
</html>
You are going to need a back-end to sync content between users, and then poll the changes to each user with AJAX.
Personally I'd recommend checking out these javascript libraries and frameworks, as they contain features close to what you're trying to achieve out-of-the-box: ShareJS, Derby and Meteor.
Just like Waiski was saying...
this is pretty old, but I would like to point out...
You are able to do this through localStorage.setItem( //itemname, //contents ),
then to fetch it, localStorage.getItem( //itemname ). for more info check out Mozilla localStorage.... You can do this temorarly but not recommended.
Good Day!
p.s. it may not work here due to not allowing you to setItem under stackoverflow because of a SecurityError, but check it out yourself!
<!DOCTYPE html>
<html>
<head>
<script>
var version = 0;
function saveEdits() {
var editElem = document.getElementById("edit");
version = localStorage.getItem("v");
var versionTxt = document.createTextNode("Version " + localStorage.getItem("v"))
document.body.appendChild(versionTxt);
version++
localStorage.setItem("v", version);
localStorage.setItem("Elm", editElem.innerHTML);
document.getElementById("update").innerHTML="Edits saved!";
}
var editedElem = document.getElementById("edit");
var edits = localStorage.getItem("Elm");
editedElem.innerHTML = edits;
</script>
</head>
<body>
<div id="edit" contenteditable="true">
Edit me
</div>
<button onclick="saveEdits()">save edits</button>
<div id="update"> - Edit the text and click to save for next time</div>
</body>
</html>

I'm trying to dynamically move elements up and down on my webpage. How do I do that?

I have a webpage that has a list of iframe soundcloud music "boxes" that play music and I want to add buttons to the side of these iframes to move the boxes up and down based on people voting on them. Kinda like what reddit has. (I'm doing this for fun and have no intention of publishing this) I tried absolute positioning the iframes and then using javascript to move the up or down but realized that would be a disaster to try to code. What would be the best way of going about this? I'm relatively new to web development.
(I used bootstrap to style the webpage)
Here is the body of the html doc:
<body>
<div class="page-header" class="stayPut"><div class="stayPut" id="Header"><img src="logo.png" ALT="Hamiltron" WIDTH=300 HEIGHT=61/></div></div>
<div class="container">
<div class="jumbotron"><h1 style="text-align: center; color: white;">An Ultimate Music List.</h1></div>
<div class="jumbotron">
<iframe id="box1" width="100%" height="150" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/113414910&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&visual=true"></iframe>
<iframe id="box2" width="100%" height="150" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/180568985&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&visual=true"></iframe>
<iframe id="box3" width="100%" height="150" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/161660686&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&visual=true"></iframe>
</div>
</div>
<script>
document.getElementById("box1").style["position"]="absolute";
document.getElementById("box1").style["top"] = "20px";
document.getElementById("box1").style["width"] = "75%";
</script>
<script src="http://code.jquery.com/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
I'd love to help so I'll show you the best way I'd do it. You will need to enable voting and a database, even just a 1 table data base with values such as
ID | VoteCount | TRACKID
0 3 180568985
If I where you I'd work on this first and then assign buttons to increase the vote count in the database. I'd do this with Ajax to poll a PHP file to connect to the database so your page doesn't reload after each vote!
Then you will need to use Javascript or get the items from the database in order when you poll them. I've created an example that will display them for you:
Working Example of Following Code | JSFiddle.com
//This is a JSON Object that can be assessed like dataFromDatabaseExample[2].vote = 100
//NOTE THESE ARE NOT IN THE RIGHT ORDER ;)
var dataFromDatabaseExample = [{id: 0, vote: 43, songID: 113414910},
{id: 1, vote: 5, songID: 180568985},
{id: 2, vote: 100, songID: 161660686}];
//Creates an event listener to listen for if someone clicks the refresh button
$('#refresh').on('click',function(){
refreshData();
});
//Function that holds main data that can be run whenever
function refreshData(){
//Clears the bit of the page where the votes are going to be ie RESET
$('#soundCloudItems').html("");
//Sort the values to be in order using our custom sorting function compareVotes
var songs = dataFromDatabaseExample.sort( compareVotes );
//For every item we got
for(var i=0;i<songs.length;i++){
//Title it (Optional but shows vote count)
$('#soundCloudItems').append("Votes: "+songs[i].vote+"<br>");
//Display the soundcloud box
$('#soundCloudItems').append(getSongCode(songs[i].id,songs[i].vote,songs[i].songID));
}
}
//Run on Load to display some data
refreshData();
//TWO HELPER FUNCTIONS ///////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
//Compares two items from the array, for the vote count
function compareVotes(a,b) {
if (a.vote > b.vote)
return -1;
if (a.vote < b.vote)
return 1;
return 0;
}
//Just returns all the bulky code in a nice form as a piece of HTML/Text
function getSongCode(id,vote,SongId){
return '<iframe data-voteCount="'+id+'" id="soundcloud'+id+'" width="100%" height="150" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/'+SongId+'&auto_play=false&hide_related=false&show_comments=true&show_user=true&show_reposts=false&visual=true"></iframe>';
}

Categories