-1

I use JavaScript to programmatically replace my whole page on a button click:

btn.addEventListener("click", evt => {
    fetch("hqsc").then(r => {
        const txt = r.text();
        txt.then(t => {
            document.querySelector('html').innerHTML = t;
            console.log(t);
        });
    }).catch(console.log);
});

The page that is intended to be loaded is as follows:

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8"></meta>

    <style type="text/css">
        body {
            background-color: lightblue;
        }

        form#authenticate {
            width: 30vw;
            height: auto;
            margin: 20vh auto;
            border: 1px dashed black;
            border-radius: 5px;
            background-color: darkgray;
            padding: 15px 10px;
            display: grid;
            grid-template-columns: 120px 100px;
            grid-column-gap: 15px;
            grid-row-gap: 20px;
            grid-column-start: 1;
            grid-row-start: 1;
        }
    </style>
    **<script type="module" src="/static/auth.js"></script>**

</head>

<body>
    <form id="authenticate">
        <label for="username">User</label>
        <input id="username" type="text" name="username" />

        <label for="password">Pass</label>
        <input id="password" type="password" name="password" />

        <input type="submit" value="Enter" />
    </form>

</body>

</html>

I noticed that the /static/auth.js javascript on the new page is completely ignored. Why is it ignored? How can I address this issue?

Jinghui Niu
  • 990
  • 11
  • 28

1 Answers1

3

Why is it ignored?

For security reasons. See this comment from https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#Security_considerations:

HTML5 specifies that a <script> tag inserted with innerHTML should not execute.

How can I address this issue?

I would first and foremost recommend you address it by finding an alternative way to update your document. Resetting the entire HTML document as a result of a user action is likely going to cause many issues; I doubt this script issue will be the last unexpected side effect you find.

If you absolutely must use this method, see this question for some ideas for how to make it work.

Hamms
  • 5,016
  • 21
  • 28
  • 1
    I agree. You can store that _other HTML_ at a different address and programmatically navigate there as in `window.location = "that-fancy-new-url";` – Raz Chiriac Apr 21 '20 at 23:18