以编程方式替换整个文档的`innerHTML`不会触发加载JS吗?

问题描述 投票:-1回答:1

通过单击按钮,我使用JavaScript以编程方式替换整个页面:

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

打算加载的页面如下:

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

我注意到新页面上的/static/auth.js javascript被完全忽略。为什么它被忽略?我该如何解决这个问题?

javascript
1个回答
1
投票

为什么它被忽略?

出于安全原因。请参阅https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#Security_considerations的评论:

HTML5指定在<script> innerHTML中插入了should not execute标签。

我该如何解决这个问题?

首先,我建议您通过寻找另一种更新文档的方法来解决它。由于用户操作而重置整个HTML文档可能会引起很多问题;我怀疑此脚本问题将是您发现的最后一个意外副作用。

如果绝对必须使用此方法,请参见this question以获取有关如何使其工作的一些想法。

© www.soinside.com 2019 - 2024. All rights reserved.