简体   繁体   中英

Programmatically replacing `innerHTML` of whole document doesn't trigger loading JS?

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM