簡體   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