Search code examples
javascripthtmlinputinnerhtmlgetelementbyid

Displaying a user input in an html tag from the other file [HTML+JS]


I am sort of building an electron app using HTML, JS and CSS - just a basic thing. I have two html files (say FILE1.html and FILE2.html).

In file1 a user provides his username/password pair, which then takes him to file2.

What I want to do is to capture user's input (username specifically) in file1 and display it in file2.

Now, I can do that within a single file; here is my code:

FILE1

<body>
  <input type="text" id="username" /><br>   
    <button onclick="getUserName(); return false;">Continue</button>
  <h1 id="receivedUserName"></h1>
</body>

and JS file:

const getUserName = () => {
  let userName = document.getElementById('username').value;
  document.getElementById('receivedUserName').innerHTML = userName;
};

All works fine within file1 but what I actually need is to pass the captured username to the FILE2.

FILE2

<form>
  <span id="receivedUserName"></span>
</form>

Just cannot think of a way to go around it ... Surely the line <h1 id="receivedUserName"></h1> in file1 is for for a single file testing.
Thank you in advance.


Solution

  • Use localStorage something like the below (I haven't tested this):

    let username = document.getElementById('username').value;
    localStorage.setItem('username', username);
    

    Then in the other file:

    let username = localStorage.getItem('username');
    document.getElementById('receivedUserName').innerText = username;
    

    VERY IMPORTANT SIDE NOTE: you must use innerText, not innerHTML to set the contents of the receivedUserName element, in case the username contains a < or &. This is not just an aesthetic thing - it will cause the app to break badly, and if ever show data from one user to another user this way, you have a huge security hole as they could put malicious script in a script tag in their username. Google XSS or Cross site scripting.