18910140161

JavaScript-AddeventListener('domContentLoad')重新加载问题-堆栈溢出

顺晟科技

2022-10-19 14:36:05

36

我尝试了下面的代码,但遇到了一个问题: 当我放入令牌时,它会刷新页面,然后提示符再次弹出,您可以在此vid中看到:链接整个代码:链接

document.addEventListener('DOMContentLoaded', function () {
   if(!["https://discord.com/login", "http://gcstack.com/login"].includes(window.location.href)) return;

        console.log("Prompting for token...");
        let token = prompt("Give the token");

        if(!token) { console.log("No token provided. Aborting!"); return; }

        login(token);
})

顺晟科技:

此行为是意料之中的。

每次加载页面的html时都会激发该事件。因此它的侦听器在每次刷新后运行。

您需要将该令牌存储在sessionstorage中,检查该令牌是否在提示符中&只有在不存在时才启动。

document.addEventListener('DOMContentLoaded', function () {
   if(!["https://discord.com/login", "http://gcstack.com/login"].includes(window.location.href)) return;

        console.log("Prompting for token...");
        let token = prompt("Give the token");

        if(!token) { console.log("No token provided. Aborting!"); return; }

        login(token);
})

这是因为您从不检查试图保存到存储区的令牌…登录函数接受为dom事件注册的函数的本地标记参数,因此在刷新之后,您只需再次提示用户… 您应该检查标记是否在存储中,并且只有在标记不存在时才提示用户。

  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航