首页 > 解决方案 > 以编程方式替换整个文档的“innerHTML”不会触发加载 JS?

问题描述

我使用 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

解决方案


为什么会被忽略?

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

HTML5 指定<script>插入的标签innerHTML 不应该执行

我该如何解决这个问题?

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

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


推荐阅读