Update two html files at the same time using javas

2019-08-07 05:38发布

问题:

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 contains an input field where an user can enter a temperature in degree celcius. This number is then converted to the temperature in Kelvin using a javascript function called "convTemp".

Problem is the output. I would like to get the result printed on both HTML pages (in "< p id="output" > text to be replaced < /p >") but currently it works only for one of the files. How can I modify the javascript file/HTML files to update both HTML files at the same time and not only one? Any comments are welcome! If it is not possible using javascript, how else could it be done?

Here are the files I use demonstrating the problem using a small toy example:

HTML file number 1:

<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, 'output')"><BR>
<p id="output">Here the output will appear and a new tab will open as well.</p>
</body>
</html>

HTML file number 2:

<html>
<head>
<title>HTML number 2</title>
<script src="JSfunc.js" type="text/javascript"></script>
</head>
<body>
<p id="output">This replacement does not work yet</p>
</body>
</html>

Javascript file:

 function convTemp(x, tID) {
     var res = parseFloat(x) + 273.15;
     window.open('htmlfile2.html'); /*, "_self" */
     document.getElementById(tID).innerHTML = x + " degrees are " + res + " Kelvin.";
}

Edit: I tried the localStorage solution but it still does not work. The js file now looks as follows:

function convTemp(x) {

   var res = parseFloat(x) + 273.15;
   /*window.open('htmlfile2.html'); /*, "_self" */


   if (typeof(Storage) != "undefined") {
        localStorage.setItem("resCalc", res);
        window.location.href = 'htmlfile2.html';
        document.getElementById("output").innerHTML = x + " degrees are  "     + localStorage.getItem("resCalc") + " Kelvin.";
    }
    else {
    document.getElementById("output").innerHTML = "Sorry, your browser does not support Web Storage...";
    }   
}

Any ideas? Thanks!

Edit 2: I added a working solution (see below). If anyone has a better solution, please post it - thanks!

回答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!



回答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
});


回答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');

}


回答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);