Skip to content Skip to sidebar Skip to footer

Update Two Html Files At The Same Time Using Javascript

I am very new to this topic so it might be a simple question but I could not answer it by googling. I have two HTML files and a javascript file (see below). The first HTML file con

Solution 1:

By using localStorage - as suggested by epascarello and Michael - I could solve the problem although I doubt that it is the most aesthetic one.

Here are the files, maybe someone else runs into this problem or can suggest a better solution later on:

htmlFile1.html:

<html>
<head>
<title>JavaScript-Test</title>
<script src="JSfunc.js" type="text/javascript"></script>
</head>
<body>
  <form name="Calc">
     <input type="text" name="myNumber" size="3">
     <input type="button" value="convert temperatures"    onclick="convTemp(document.Calc.myNumber.value)"><BR>
  <div id="output">Here the output will appear and a new tab will open as well.</div>
</html>

htmlfile.2.html:

<html>
<head>
<title>HTML number 2</title>
<script src="JSfunc.js" type="text/javascript"></script>
</head>
<body>
    <div id="output">This replacement does work now.</div>
    <script>showData();</script>
</body>
</html>

And the js file JSfunc.js:

function convTemp(x) {

   var res = parseFloat(x) + 273.15;

   if (typeof(Storage) != "undefined") {
        //localStorage.setItem("resCalc", resString);
        setData("resCalc", res.toString());
        setData("origVal", x);
        showData();
        window.open('htmlfile2.html'); //, "_self" 
    }
    else {
    document.getElementById("output").innerHTML = "Sorry, your browser does not support Web Storage...";
    }

}

function setData(tfield, tval)
{
    localStorage.setItem(tfield, tval);
}

function showData()
{
    var tstr = localStorage.getItem("resCalc");
    var x = localStorage.getItem("origVal");

    document.getElementById("output").innerHTML = x + " degrees are " + tstr + " Kelvin.";  
}

Comments/improvements are always welcome!


Solution 2:

I think you need postMessage to do this. You can send a message to other window so that you can update both.

Maybe:

var otherwindow = window.open("htmlfile2.html");
otherwindow.postMessage({ x: x, res: res }, "*");

And in HTML file number 2:

window.addEventListener("message", function (ev) {
  // Update your HTML using ev.data
});

Solution 3:

You can only alter the current DOM with javascript, but you can use e.g. cookies to get the data displayed on both pages after changing those on one page. Preferably, if you use php or any server side language too, the way to go would be to save the entries in your database and pull them from there.

here's a function taken from this answer to create and retrieve cookies.

var createCookie = function(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

USAGE:

Set the cookie:

<html>
<head>
<title>JavaScript-Test</title>
<script src="JSfunc.js" type="text/javascript"></script>
</head>
<body>
<form name="Calc">
<input type="text" name="myNumber" id="myNumber" size="3">
<input type="button" value="convert temperatures" onclick="convTemp(document.Calc.myNumber.value, 'output')"><BR>
<p id="output">Here the output will appear and a new tab will open as well.</p>
</body>
</html>

JSFunc.js:

document.onload = function(){
document.getElementById('myNumber').addEventListener('keyup', addtoCookie);
function addtoCookie() {
var inputs = document.getElementById('myNumber').value

var createCookie = function(name, value, days) {
    var expires;
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    else {
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}
createCookie('entry',inputs,30);
}
}

You can then load the content from the cookie on page load:

<html>
<head>
<title>JavaScript-Test Page2</title>
<script src="JSfunc2.js" type="text/javascript"></script>
</head>
<body>

<p id="output">Here the output will appear and a new tab will open as well.</p>
</body>
</html>

JSFunc2.js (let's say the cookie is called 'entry'):

document.onload=function() {
function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

 document.getElementById('output').innerHTML = getCookie('entry');

}

Solution 4:

Send it in the querystring

window.open('htmlfile2.html?temp=' + encodeURIComponent(res));

read it on the next page

function getParameterByName(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
    return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}

var temp = getParameterByName('temp');
console.log(temp);

Post a Comment for "Update Two Html Files At The Same Time Using Javascript"