Transfer data from one HTML file to another - javascript

I'm new to HTML and JavaScript, what I'm trying to do is from an HTML file I want to extract the things that set there and display it to another HTML file through JavaScript.
Here's what I've done so far to test it:
testing.html
<html>
<head>
<script language="javascript" type="text/javascript" src="asd.js"></script>
</head>
<body>
<form name="form1" action="next.html" method="get">
name:<input type ="text" id="name" name="n">
<input type="submit" value="next" >
<button type="button" id="print" onClick="testJS()"> Print </button>
</form>
</body>
</html>
next.html
<head>
<script language="javascript" type="text/javascript" src="asd.js"></script>
</head>
<body>
<form name="form1" action="next.html" method="get">
<table>
<tr>
<td id="here">test</td>
</tr>
</table>
</form>
</body>
</html>
asd.js
function testJS()
{
var b = document.getElementById('name').value
document.getElementById('here').innerHTML = b;
}
test.html -> ads.js(will extract value from the test.html and set to next.html) -> next.html

Try this code:
In testing.html
function testJS() {
var b = document.getElementById('name').value,
url = 'http://path_to_your_html_files/next.html?name=' + encodeURIComponent(b);
document.location.href = url;
}
And in next.html:
window.onload = function () {
var url = document.location.href,
params = url.split('?')[1].split('&'),
data = {}, tmp;
for (var i = 0, l = params.length; i < l; i++) {
tmp = params[i].split('=');
data[tmp[0]] = tmp[1];
}
document.getElementById('here').innerHTML = data.name;
}
Description: javascript can't share data between different pages, and we must to use some solutions, e.g. URL get params (in my code i used this way), cookies, localStorage, etc.
Store the name parameter in URL (?name=...) and in next.html parse URL and get all params from prev page.
PS. i'm an non-native english speaker, will you please correct my message, if necessary

The old fashioned way of setting a global variable that persist between pages is to set the data in a Cookie. The modern way is to use Local Storage, which has a good browser support (IE8+, Firefox 3.5+, Chrome 4+, Android 2+, iPhone 2+). Using localStorage is as easy as using an array:
localStorage["key"] = value;
... in another page ...
value = localStorage["key"];
You can also attach event handlers to listen for changes, though the event API is slightly different between browsers. More on the topic.

Assuming you are talking about this js in browser environment (unlike others like nodejs), Unfortunately I think what you are trying to do isn't possible simply because this is not the way it is supposed to work.
Html pages are delivered to the browser via HTTP Protocol, which is a 'stateless' protocol. If you still needed to pass values in between pages, there could be 3 approaches:
Session Cookies
HTML5 LocalStorage
POST the variable in the url and retrieve them in next.html via window object

With the Javascript localStorage class, you can use the default local storage of your browser to save (key,value) pairs and then retrieve these values on whichever page you need using the key.
Example -
Pageone.html -
<script>
localStorage.setItem("firstname", "Smith");
</script>
Pagetwo.html -
<script>
var name=localStorage.getItem("firstname");
</script>

I use this to set Profile image on each page.
On first page set value as:
localStorage.setItem("imageurl", "ur image url");
or on second page get value as :
var imageurl=localStorage.getItem("imageurl");
document.getElementById("profilePic").src = (imageurl);

you can simply send the data using window.location.href first store the value to send from testing.html in the script tag, variable say
<script>
var data = value_to_send
window.loaction.href="next.htm?data="+data
</script>
this is sending through a get request

HI im going to leave this here cz i cant comment due to restrictions but i found AlexFitiskin's answer perfect, but a small correction was needed
document.getElementById('here').innerHTML = data.name;
This needed to be changed to
document.getElementById('here').innerHTML = data.n;
I know that after five years the owner of the post will not find it of any importance but this is for people who might come across in the future .

<html>
<head>
<script language="javascript" type="text/javascript" scr="asd.js"></script>
</head>
<body>
<form name="form1" action="#" method="get">
name:<input type ="text" id="name" name="n">
<input type="submit" value="next" >
<button type="button" id="print" onClick="testJS()"> Print </button>
</form>
</body>
client side scripting
function testJS(){
var name = jQuery("#name").val();
jQuery.load("next.html",function(){
jQuery("#here").html(name);
});
}
jQuery is a js library and it simplifies its programming. So I recommend to use jQuery rathar then js. Here I just took value of input elemnt(id = name) on submit button click event ,then loaded the desired page(next.html), if the load function executes successfully i am calling a function which will put the data in desired place.
jquery load function http://api.jquery.com/load/

The following is a sample code to pass values from one page to another using html. Here the data from page1 is passed to page2 and it's retrieved by using javascript.
1) page1.html
<!-- Value passing one page to another
Author: Codemaker
-->
<html>
<head>
<title> Page 1 - Codemaker</title>
</head>
<body>
<form method="get" action="page2.html">
<table>
<tr>
<td>First Name:</td>
<td><input type=text name=firstname size=10></td>
</tr>
<tr>
<td>Last Name:</td>
<td><input type=text name=lastname size=10></td>
</tr>
<tr>
<td>Age:</td>
<td><input type=text name=age size=10></td>
</tr>
<tr>
<td colspan=2><input type=submit value="Submit">
</td>
</tr>
</table>
</form>
</body>
</html>
2) page2.html
<!-- Value passing one page to another
Author: Codemaker
-->
<html>
<head>
<title> Page 2 - Codemaker</title>
</head>
<body>
<script>
function getParams(){
var idx = document.URL.indexOf('?');
var params = new Array();
if (idx != -1) {
var pairs = document.URL.substring(idx+1, document.URL.length).split('&');
for (var i=0; i<pairs.length; i++){
nameVal = pairs[i].split('=');
params[nameVal[0]] = nameVal[1];
}
}
return params;
}
params = getParams();
firstname = unescape(params["firstname"]);
lastname = unescape(params["lastname"]);
age = unescape(params["age"]);
document.write("firstname = " + firstname + "<br>");
document.write("lastname = " + lastname + "<br>");
document.write("age = " + age + "<br>");
</script>
</body>
</html>

I coded the answers from Alex Fitiskin, and added a bit of extra code.
I added a parameter to the onLoad function to get the form's submit event, and prevent it's default behaviour first.
Here's the code:
test.html
<html>
<head>
<script language="javascript" type="text/javascript" src="test.js"></script>
</head>
<body>
<form name="form1" action="next.html" method="get" onsubmit="return testJS(event)">
name:<input type="text" id="name" name="n">
<input type="submit" value="next">
<!-- <button type="button" id="print" onClick="testJS()"> Print </button> //Button not needed anymore -->
</form>
</body>
</html>
next.html
<head>
<script language="javascript" type="text/javascript" src="test.js"></script>
</head>
<body>
<form name="form1" action="next.html" method="get">
<table>
<tr>
<td id="here">test</td>
</tr>
</table>
</form>
</body>
</html>
test.js
function testJS(e) {
e.preventDefault();
var b = document.getElementById('name').value,
url = 'http://path_to_next_location/next.html?name=' + encodeURIComponent(b);
document.location.href = url;
}
function onLoad() {
var url = document.location.href,
params = url.split('?')[1].split('&'),
data = {},
tmp;
for (var i = 0, l = params.length; i < l; i++) {
tmp = params[i].split('=');
data[tmp[0]] = tmp[1];
}
document.getElementById('here').innerHTML = data.name;
}
window.onload = onLoad;
This way the onload function will be replaced with the custom onLoad function, and the form will not be submitted the default way, but instead using the code inside the testJS function.

Avoid localstorage use as data are not safe with get method. Best option is to use script set to module and then export & import data via 2 js files to html file. Variable value can be passed between pages using module method.

Related

Is it possible to have XSS vulnerability in a client side web application?

I'm new to security concepts. I have a program that is written in javascript and therefore can only be run in the browser. I was wondering is there any way to inject javascript code in this program?
My program looks like this:
index.html:
<form method="get" action="file.html">
Enter your name: <input name="name" type="text"> <input type="submit" value="enter">
</form>
file.html:
<head>
<script src="js/main.js"></script>
</head>
<body>
<div id="contents">
</div>
</body>
js/main.js:
function get_parameters() {
// 1. get the string of the get parameters after question mark
var parameters = window.location.search.substr(1);
// 2. make an array of parameters
parameters = parameters.split('&')
// 3. retrieve parameters
var res = {}
parameters.forEach(function (item) {
var tmp = item.split('=');
res[tmp[0]] = decodeURIComponent(tmp[1]);
})
// 4. return parameters
return res;
}
window.onload = function () {
var parameters = get_parameters();
if ('name' in parameters) {
document.getElementById('contents').innerHTML = '<div> Hello ' + parameters['name'] + '</div>';
}
};
Scripts can be inserted via the url. If you visit file.html?name=%3Cimg%20onerror%3Dalert(1)%20src%3D/%3E then you should see an alert.
The use of the innerHTML property is setting HTML containing user controlled content. If instead you use innerText then it wouldn't be possible. For example:
document.getElementById('contents').innerText = 'Hello ' + parameters['name'];

html script variable assignment

So I have a script block:
<script>
var totalPopulation = 0;
for(xxxxx){
totalPopulation = totalPopulation + xxx
}
</script>
<tr>
<input type="text" name="censusPop" value=totalPopulation/>
<tr>
I'm still quite green to javascript. But is there a way to assign the value of a variable in a script block to a HTML element like input type? I know that the code is unreachable.
hope it will help you to understand how javascript work
<html>
<head>
<script>
var totalPopulation = 0;
function addAndShowPopulation(population) {
totalPopulation = totalPopulation + population;
var input_tag = getTag('my_input_id');
input_tag.value = totalPopulation;
}
function startAdding() {
addAndShowPopulation(10);
setTimeout( function(){startAdding();},1000);
}
function getTag(id) {
return document.getElementById(id);
}
</script>
</head>
<body onload="startAdding();">
<div>
<input type="text" id="my_input_id" name="censusPop" value="" placeholder="Total Population"/>
</div>
</body>
</html>
Yes, you just have to give an id to the input, for instance "id = my_input_id";
Then, in the javascript, just write :
$("my_input_id").value=totalPopulation;
That's how ajax works: find html elements ids and fill them dinamically using javascript values.
Just be carefull that the html in read before the JS. If not, $("my_input_id") will return Null
More so, you need to do something like this:
<tr>
<td>
<input type="text" id="censusPop" name="censusPop" value=""/>
<td>
<tr>
<!-- Other stuff -->
<script>
var totalPopulation = 10;
// or for loop, or whatever here.
var censusText = document.getElementById('censusPop');
censusText.value = totalPopulation;
</script>
</body>
HTML and JavaScript can interact, but not directly like that. The best thing to do is use <script> tags to setup code that updates the browser DOM. By putting the <script> tags after the HTML, usually at the bottom of the <body> tag, you allow the browser a chance to create the elements before you actually try to use them.
Another note: <tr> tags should contain <td> tags, it's the difference between a row and a column.
If you need to do multiple DOM manipulations, I'd suggest using jQuery is the proper way.
<tr>
<input id="censusPop" type="text" name"censusPop" value=""/>
</tr>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
// make sure, the code is executed when the DOM is ready
$(function () {
// grab the input element by its ID
var $input = $('#censusPop'),
totalPopulation = 0;
// do your population calculations
totalPopulation = ....;
// assign the value to the input element
$input.val(totalPopulation);
});
</script>

Posting form values securely from one page to another on client-side using pure Javascript and NO server-side technology

I need to POST form values from one page to another using Javascript.
Now, I know that I could use a server-side technology like ASP.Net or PHP to post values but I am not allowed to use any server side script.
I am aware that using the GET method, I can pass the form values as a query string but the values will not be passed securely (which is an important requirement!)
The conditions listed below:
This code should take the values that are posted to the page and
repost to target page. HTTP POST only (not get).
In no cases, even error, the request should not stop on this bridge page.
The script needs to handle multiple posted values.
Try to use standard javascript (no 3rd party library)
Script needs to work in IE, FF, Safari, most standard browsers
Can anyone please help me find a solution to this or point me to some resource that will help me find the soln? Thanks in advance. Below is the code for passing values as a query string. Can I modify this so that my above requirements are satisfied?
FORM
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function goto_page(page) {
var usbnum = document.getElementById('usbnum').value;
var usbcode = document.getElementById('usbcode').value;
var q_str = '?usbnum=' + usbnum + '&usbcode=' + usbcode;
var url = page + q_str;
window.location = url;
}
</script>
</head>
<form id="form1" method="post">
<div>
USB No: <input name="usbnum" id="usbnum" type="text" size="80" /><br />
USB Code: <input name="usbcode" id="usbcode" type="text" size="80"/>
</div>
Next
</form>
</body>
</html>
BRIDGE PAGE
<html>
<head>
<title>Bridge Page</title>
<script type="text/javascript">
function get_params() {
var url = window.location.href;
var q_str_part = url.match(/\?(.+)$/)[1];
var val_pairs = q_str_part.split('&');
var params = {};
for (var i = 0; i < val_pairs.length; i++) {
var tmp = val_pairs[i].split('=');
params[tmp[0]] = typeof tmp[1] != 'undefined' ? tmp[1] : '';
}
return params;
}
function write_params() {
var params = get_params();
var txt = 'Hello ';
for (var i in params) {
txt += params[i] + ' ';
}
var body = document.getElementsByTagName('body')[0];
body.innerHTML += txt;
}
function write_params() {
var params = get_params();
var num_container = document.getElementById('usbnum');
var code_container = document.getElementById('usbcode');
num_container.innerHTML = params.usbnum;
code_container.innerHTML = params.usbcode;
}
</script>
</head>
<body onLoad="write_params()">
</body>
</html>
POST data can only be handled by server side code. There is no way you can use them in your javascript without help from a server side code.
You can only use GET or you can think about cookies. But at other hand, why do you want to change current page?! you can use AJAX to load more data without refreshing and no need of posting or getting variables.

JavaScript display new page when submit HTML form

Suppose I have 2 html files: form.html and confirm.html
form.html just have a text field and a submit button, when you hit submit it will display what you just typed in text field.
<HTML>
<HEAD>
<TITLE>Test</TITLE>
<script type="text/javascript">
function display(){
document.write("You entered: " + document.myform.data.value);
}
</script>
</HEAD>
<BODY>
<center>
<form name="myform">
<input type="text" name="data">
<input type="submit" value="Submit" onClick="display()">
</form>
</BODY>
</HTML>
Now I want that when hit submit button it will display entered value in confirm.html. What should I do? I mean what should be in confirm.html and how data from form.html be used in other location, do I need create a separate JavaScript file to store JS function so I can use it in both 2 html files. I am kind of new to all kind of stuff.
Note: No PHP or server side language or anything super here, just 2 html files in my Desktop and I want to test using FireFox.
Thank you!
You can try using localStorage or cookies. Check one of the 2 solutions found below...
1 - If you have HTML5, you can store the content of you input into the localStorage.
Try this example:
form.html:
<html>
<head>
<title>Test</title>
<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="confirm.html">
<input id="mytext" type="text" name="data">
<input type="submit" value="Submit">
</form>
</body>
</html>
confirm.html:
<html>
<head>
<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("passed value = "+mytext);
}
</script>
</head>
<body onload="init();">
</body>
</html>
2 - Also, as #apprentice mentioned, you can also use cookies with HTML standards.
Try this example:
form.html:
<html>
<head>
<title>Test</title>
<script type="text/javascript">
// Function for storing to cookie
function setCookie(c_name,value,exdays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
document.cookie=c_name + "=" + c_value;
}
// 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 a cookie
setCookie("mytext", mytext, 300);
return true;
}
</script>
</head>
<body>
<center>
<!-- INLCUDING `ONSUBMIT` EVENT + ACTION URL -->
<form name="myform" onsubmit="tosubmit();" action="confirm.html">
<input id="mytext" type="text" name="data">
<input type="submit" value="Submit">
</form>
</body>
</html>
confirm.html:
<html>
<head>
<script>
// Function for retrieveing value from a cookie
function getCookie(c_name)
{
var i,x,y,ARRcookies=document.cookie.split(";");
for (i=0;i<ARRcookies.length;i++)
{
x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
x=x.replace(/^\s+|\s+$/g,"");
if (x==c_name)
{
return unescape(y);
}
}
}
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into a cookie
var mytext = getCookie("mytext");
// Writing the value in the document
document.write("passed value = "+mytext);
}
</script>
</head>
<body onload="init();">
</body>
</html>
What you could do is submit the form using a get method (method="get"), and send it to your confirm.html page (action="./confirm.html").
Then, you could use jQuery to retrieve the values from the URL from your confirm.html page.
This website provides a method to do that: http://jquerybyexample.blogspot.com/2012/06/get-url-parameters-using-jquery.html .
Then, all you have to do is call your display() method.
Seams like a fit for persist.js, which will let you save and load data in the user's browser. After including its javascript file, you can save data like this:
var store = new Persist.Store('My Application');
store.set('some_key', 'this is a bunch of persistent data');
And you can later retrieve the saved data in another html page like the following:
var store = new Persist.Store('My Application');
val = store.get('some_key');
You could also, instead of changing the page, change the content of the page. Upon submission just change the page using the innerHtml variable.

Javascript changing values inside a iframe

I have my website
www.aplicatii-iphone.ro
and another
page.html on localhost
<html>
<head>
<title>Object References across Iframes</title>
<script type="text/javascript">
window.onload = function(){
var form = document.getElementById('testForm');
form.testBtn.onclick = sendData;
}
function notify() {
//alert('iframe loaded');
var iframeEl = document.getElementById('ifrm');
if ( iframeEl && iframeEl.parentNode && document.createElement ) {
var newTxt = document.createTextNode('The iframe has loaded and your browser supports it\'s onload attribute.');
var newPara = document.createElement("p");
newPara.className = 'demo';
newPara.appendChild(newTxt);
iframeEl.parentNode.insertBefore(newPara, iframeEl);
}
}
function sendData() { // to form inside iframed document
// frames array method:
// window.frames['ifrm'].document.forms['ifrmTest'].elements['display'].value = this.form.testEntry.value;
var ifrm = document.getElementById('ifrm');
var doc = ifrm.contentDocument? ifrm.contentDocument: ifrm.contentWindow.document;
var form = doc.getElementById('search-input'); // <------<< search input
form.display.value = this.form.testEntry.value;
form.submit();
}
// test in iframed doc
var counter = 0;
</script>
</head>
<body>
<form id="testForm" action="#">
<p><input type="text" name="testEntry" size="30" value="[enter something]" /> <input name="testBtn" type="button" value="Click Me" /></p>
</form>
<iframe name="ifrm" id="ifrm" src="http://www.aplicatii-iphone.ro" onload="notify()" width="900">Sorry, your browser doesn't support iframes.</iframe>
</body>
</html>
And every time I press the button Click Me, I want that the state of www.aplicatii-iphone.ro to be like a user searched for that value written in "testEntry" from outside of the iframe.
I tried something there ... but I can't figure it out ... any help please?
I took the example from here http://www.dyn-web.com/tutorials/iframes/refs.php
If you know you're using a modern browser, you could use postMessage to communicate between the frames. Here's a good write-up: http://ajaxian.com/archives/cross-window-messaging-with-html-5-postmessage
If you need to support legacy browsers, you could use Google Closure's CrossPageChannel object to communicate between frames.
Unfortunatly, this is not possible due to the Same orgin policy.
And changing the document.domain-value only helps if you try to connect a subdomain with the main-domain.
Edit
If you avoid the same-orgin-problem by using a page on the same website, this should work for you:
window.frames['ifrm'].document.getElementById("search-input").value = document.getElementsByName("testEntry")[0].value;
window.frames['ifrm'].document.getElementById("cse-search-box").submit();

Categories