繁体   English   中英

防止用户在加载 Javascript 之前提交登录表单

[英]Prevent user from submitting login form before Javascript is loaded

我们在 React App 中有一个登录表单。 我们使用服务器端渲染。 一些用户能够在加载 JavaScript 之前提交表单。 结果是用户登录尝试失败以及包含用户登录凭据的默认表单 GET 请求的日志消息。 两者都不好。

这是我们生成的表单:

<form>
    <input aria-invalid="false" autocomplete="user" id="user" name="user" type="text" aria-label="Benutzername"
        value="">
    <input aria-invalid="false" autocomplete="current-password" id="password" name="password" type="password"
        aria-label="Passwort" value="">
    <button tabindex="0" type="submit" data-e2e="einloggen-button" aria-disabled="false">Einloggen</button>
</form>

我认为这可能是服务器端渲染的常见问题。 是否有解决方案让用户无法发送表单而我们仍然可以拥有有效的 HTML?

如果您想在文档加载之前禁用提交,您可以在您的 head 标签中使用此代码。

 <script>
    document.forms[0].querySelector('button').disabled = true;
    document.onload = () => {
         document.forms[0].querySelector('button').disabled = false;
    }
 </script>

您可以在 DOM 加载期间使用 pointer-events: none,并在页面完全加载时禁用它:

document.onreadystatechange = function() {
  const body = document.querySelector("body");
  if (document.readyState === "loading") {
    console.log("Page is loading"); // Not running
  } else if (document.readyState === "interactive") {
    console.log("DOM is Loaded");
    body.style = 'pointer-events: none;' // Button disabled on click
  } else {
    console.log("Page is loaded");
    // body.style = 'pointer-events: auto;'
  }
};

在这里您可以在Repl.it上找到现场示例

您也可以只在 HTML 上添加必填字段,这将避免您的用户提交空表单。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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