document.write appends null in ChromeOs

42 Views Asked by At

I parse two values to my print.html file like this: .../print.html?name=Peter%20Gram&city=Torshavn. In the file I receive them like this:

<script>
const name = urlParams.get('name')
const city = urlParams.get('city')

and output it like this:

...
<tr><td>Name:<br><script>document.write(name)</script>
<tr><td>City:<br><script>document.write(city)</script>
...

Doing so I get

Name: Peter Gramnull

City: Torshavn

Why does ChromeOS append the "null"? It only occurs on Chromebook, not on my windows PC (Chrome browser). In my real life situation I pass 5 parms. Three of them have a space in them (%20) and all of those three come out with the "null" appended.

1

There are 1 best solutions below

6
mplungjan On BEST ANSWER

Show urlParams please.

I suggest this:

window.addEventListener("DOMContentLoaded", () => { // when page has loaded
  const url = new URL(`https://example.com/print.html?name=Peter%20Gram&city=Torshavn`)
  const name = url.searchParams.get("name");
  const city = url.searchParams.get("city");
  document.getElementById("name").textContent = name;
  document.getElementById("city").textContent = city;

  // using queryString:

  const urlParams = new URLSearchParams(`?name=Peter%20Gram&city=Torshavn`);
  const n = urlParams.get('name')
  document.getElementById("b").textContent = n;
});
<table>
  <tbody>
    <tr>
      <td>Name:<br/><span id="name"></span></td>
    </tr>
    <tr>
      <td>City:<br/><span id="city"></span></td>
    </tr>
    <tr>
      <td colspan="2">Still works:<br/><span id="b"></span></td>
    </tr>
  </tbody>
</table>