HTML/JS格式 |电子邮件 JS 错误:未捕获(在 promise 中) 错误:侦听器通过返回 true 来指示异步响应,但消息通道已关闭

HTML/JS | Email JS Error: Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed

提问人:AJ PHIL 提问时间:7/23/2023 最后编辑:marc_sAJ PHIL 更新时间:11/12/2023 访问量:420

问:

我在“联系我们”代码中使用 HTML/CSS/JS 和电子邮件 JS,这是它在下面显示的完整错误;请注意,“联系我们”表单在单击时使用电子邮件 JS 进行验证和发送电子邮件。

未捕获(在 promise 中)错误:侦听器通过返回 true 来指示异步响应,但消息通道在收到响应之前关闭

我是如何得出这个错误的,是我试图在“联系提交表单”按钮中使用两次点击,我使用下面的代码解决了这个问题;

    <div class="col-md-6 animate" data-animate="fadeInUp">
        <form id="ajax-contact" name="mydata" action="/index.html" method="POST">
            <div class="input-field">
                <input type="text" class="form-control" name="name" id="name"
                    placeholder="Name">
                <div class="error" id="name_err"></div>
            </div>
            <div class="input-field">
                <input type="email" class="form-control" name="email" id="email"
                    placeholder="Email">
                <div class="error" id="email_err"></div>
            </div>
            <div class="input-field">
                <textarea class="form-control" name="message" id="message"
                    placeholder="Message"></textarea>
                <div class="error" id="message_err"></div>
            </div>
            <button class="btn" type="submit" onclick="submitForm(event)">Submit
            </button>
        </form>
        <!-- <div id="form-messages" class="mt-3"></div> -->
    </div>

请注意,即使我删除了 onclick的事件,例如 onclick=“submitForm()”,它仍然不会发送电子邮件。

下面是我的验证代码,该文件名为validateContact.js我将使用电子邮件JS代码发送电子邮件合并为一个文件,如下所示:

function printError(elemId, hintMsg){
    document.getElementById(elemId).innerHTML = hintMsg;
}

function contactUs(){ 
    var name = document.mydata.name.value;
    var email = document.mydata.email.value;
    var message = document.mydata.message.value;
    
    // ___ Defining error variables with default value
    var name_err = email_err = message_err = true;

    // _______ validating Name
    if(name === ""){
        printError("name_err", "Please Enter Your Name");
        const errId = document.getElementById('name');
        errId.style.border = '1px solid red';
    }
    else  if(name.length < 5 || name.length > 50){
        printError("name_err", "Names should be between 5-50 characters");
        const errId = document.getElementById('name');
        errId.style.border = '1px solid red';
    }
    else{
        var regex = /^[a-zA-Z\s]+$/;
        if(regex.test(name) === false){
            printError("name_err", "Names should not include numeral characters.");
            const errId = document.getElementById('name');
            errId.style.border = '1px solid red';
        }else{
            var uppercase = /^[A-Z][a-z]* [A-Z][a-z]*/;
            if(uppercase.test(name) === false){
            printError("name_err", "First letter of Name should be In Uppercase i.e Phil Ubuntu");
            const errId = document.getElementById('name');
            errId.style.border = '1px solid red';
        }else{
            printError("name_err", "");
            name_err = false;
        }
        }
    }

    // _______ validating Email Info
    if(email === ""){
        printError("email_err", "Email cannot be left Empty");
        const errId = document.getElementById('email');
        errId.style.border = '1px solid red';
    }else{
        var letters = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;;
        if(letters.test(email) === false){
            printError("email_err", "Invalid Email(Include @)")
            const errId = document.getElementById('email');
            errId.style.border = '1px solid red';
        }else{
            printError("email_err", "");
            email_err = false;
        }
    }

    // _______ validating message
    if(message === ""){
        printError("message_err", "Please Enter Your Message");
        const errId = document.getElementById('message');
        errId.style.border = '1px solid red';
        }    else{
            var uppercase = /^[A-Z][a-z]*/;
            if(uppercase.test(message) === false){
                printError("message_err", "First letter Should be In CapsLock e.g This is..");
                const errId = document.getElementById('message');
                errId.style.border = '1px solid red';
            }else{
            printError("message_err", "");
            message_err = false;
        }
    }

    // // __Preventing the form from being submited if their are any errors
    // if(( name_err || email_err || message_err) === true){
    //     // Temporary removing this as suggested by ChatGPT when calling 2 function on submit button
    //     // we removed the event.preventDefault don't use this code in other project.
    //     // event.preventDefault()
    // }else{
    //     event.currentTarget.submit()
    // }  
}

    // Send Email      
    function sendMail() {
        var params = {
          name: document.getElementById("name").value,
          email: document.getElementById("email").value,
          message: document.getElementById("message").value,
        };
      
        const serviceID = "service_0vlh0ul";
        const templateID = "template_9n4gyyb";
      
          emailjs.send(serviceID, templateID, params)
          .then(res=>{
              document.getElementById("name").value = "";
              document.getElementById("email").value = "";
              document.getElementById("message").value = "";
              console.log(res);
              alert("Your message sent successfully!!")
      
          })
          .catch(err=>console.log(err));
      }

    // async function sendMail() {
    //     var params = {
    //       name: document.getElementById("name").value,
    //       email: document.getElementById("email").value,
    //       message: document.getElementById("message").value,
    //     };
      
    //     const serviceID = "service_0vlh0ul"; // Replace with your EmailJS service ID
    //     const templateID = "template_9n4gyyb"; // Replace with your EmailJS template ID
      
    //     try {
    //       const result = await emailjs.send(serviceID, templateID, params);
    //       console.log(result);
    //       alert("Your message sent successfully!!");
    //       // Clear the form fields after successful submission
    //       document.getElementById("name").value = "";
    //       document.getElementById("email").value = "";
    //       document.getElementById("message").value = "";
    //     } catch (error) {
    //       console.error("Error sending email:", error);
    //     }
    //   }

      function submitForm() {
        // Call contactUs() first to perform validation
        contactUs();

          // Prevent the default form submission
        event.preventDefault();
      
        // Check if the validation was successful before proceeding with sending email
        if (!name_err && !email_err && !message_err) {
          // If validation passes, call the sendMail() function to submit the form data via emailJS
          sendMail();
        } else {
          // If there are validation errors, do nothing. The form will not submit.
        }
      }

请注意,在我的索引 .js 文件中,我的标题标签中有电子邮件 .JS 脚本,如下所示:

<head>
    <script src="js/validateContact.js"></script>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/@emailjs/browser@3/dist/email.min.js">
    </script>
    <script type="text/javascript">
        (function () {
            emailjs.init("NMjjGTpQTLxIksxsp");
        })();
    </script>
</head>

现在我尝试解决 Uncaught In Promise 错误,因为 ChatGPT 告诉我这是由如下所示引起的,但它仍然没有发送电子邮件:

错误消息“Uncaught (in promise) Error: A listener indicates 通过返回 true 的异步响应,但消息通道 在收到响应之前已关闭“与已知问题相关 使用 emailjs-com 库。如果有比赛,则可能会出现此问题 emailjs-com 库和表单提交之间的条件, 导致消息通道在收到响应之前关闭 来自 EmailJS。

要解决此问题,您可以使用旧版本的 emailjs-com 库 (v2.6.4),因为它没有这个特定问题。这是 如何在 HTML 文件中包含正确的版本:

html 复制代码

<script src="https://cdn.emailjs.com/dist/email.min.js"></script>
Ensure that you are including the version 2.6.4 of the emailjs-com library, as newer versions may still have the issue.

此外,为了防止任何其他潜在的竞争条件,您可以 修改 sendMail() 函数以使用 async/await 语法。这 将确保在进一步进行之前解决承诺。 以下是更新后的 sendMail() 函数:

javascript 复制代码

async function sendMail() {
  var params = {
    name: document.getElementById("name").value,
    email: document.getElementById("email").value,
    message: document.getElementById("message").value,
  };

  const serviceID = "YOUR_EMAILJS_SERVICE_ID"; // Replace with your EmailJS service ID
  const templateID = "YOUR_EMAILJS_TEMPLATE_ID"; // Replace with your EmailJS template ID

  try {
    const result = await emailjs.send(serviceID, templateID, params);
    console.log(result);
    alert("Your message sent successfully!!");
    // Clear the form fields after successful submission
    document.getElementById("name").value = "";
    document.getElementById("email").value = "";
    document.getElementById("message").value = "";
  } catch (error) {
    console.error("Error sending email:", error);
  }
}

通过这些更改,应解决争用条件问题,并且 sendMail() 函数应该可以正常工作,而不会抛出 提到的错误。表单后应成功发送电子邮件 验证通过。

请注意,使用旧版本的库是临时的 解决方法,直到问题在较新版本中得到解决。一定要 请密切关注 emailjs-com 库的更新,了解任何改进或 在将来的版本中修复。

请注意,在验证.js电子邮件.js文件之前,在我将它们合并为一个 onclick 之前,onclick=“submitForm(event)” 工作正常。

竟然!现在,在恢复代码并且不使用异步 await 并返回我的原始代码后,它现在没有显示任何错误,因为下面的屏幕截图,还有其他错误,除非我混淆了它们,否则请忽略它们,但截至目前,您可以看到没有“未捕获(在承诺中)错误: 侦听器通过返回 true 来指示异步响应,但消息通道在收到响应之前关闭“Console No Email.JS Uncaught Promise Error

在我合并并更改代码之前,我将发送原始验证 .js 和原始电子邮件 .js 文件,以便它们可以在一次点击中工作。

验证.js文件原始

    function printError(elemId, hintMsg){
        document.getElementById(elemId).innerHTML = hintMsg;
    }
    
    function contactUs(){ 
        var name = document.mydata.name.value;
        var email = document.mydata.email.value;
        var message = document.mydata.message.value;
        
        // ___ Defining error variables with default value
        var name_err = email_err = message_err = true;
    
        // _______ validating Name
        if(name === ""){
            printError("name_err", "Please Enter Your Name");
            const errId = document.getElementById('name');
            errId.style.border = '1px solid red';
        }
        else  if(name.length < 5 || name.length > 50){
            printError("name_err", "Names should be between 5-50 characters");
            const errId = document.getElementById('name');
            errId.style.border = '1px solid red';
        }
        else{
            var regex = /^[a-zA-Z\s]+$/;
            if(regex.test(name) === false){
                printError("name_err", "Names should not include numeral characters.");
                const errId = document.getElementById('name');
                errId.style.border = '1px solid red';
            }else{
                var uppercase = /^[A-Z][a-z]* [A-Z][a-z]*/;
                if(uppercase.test(name) === false){
                printError("name_err", "First letter of Name should be In Uppercase i.e Phil Ubuntu");
                const errId = document.getElementById('name');
                errId.style.border = '1px solid red';
            }else{
                printError("name_err", "");
                name_err = false;
            }
            }
        }
    
        // _______ validating Email Info
        if(email === ""){
            printError("email_err", "Email cannot be left Empty");
            const errId = document.getElementById('email');
            errId.style.border = '1px solid red';
        }else{
            var letters = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;;
            if(letters.test(email) === false){
                printError("email_err", "Invalid Email(Include @)")
                const errId = document.getElementById('email');
                errId.style.border = '1px solid red';
            }else{
                printError("email_err", "");
                email_err = false;
            }
        }
    
        // _______ validating message
        if(message === ""){
            printError("message_err", "Please Enter Your Message");
            const errId = document.getElementById('message');
            errId.style.border = '1px solid red';
            }    else{
                var uppercase = /^[A-Z][a-z]*/;
                if(uppercase.test(message) === false){
                    printError("message_err", "First letter Should be In CapsLock e.g This is..");
                    const errId = document.getElementById('message');
                    errId.style.border = '1px solid red';
                }else{
                printError("message_err", "");
                message_err = false;
            }
        }
    
        // __Preventing the form from being submited if their are any errors
        if(( name_err || email_err || message_err) === true){
            // Temporary removing this as suggested by ChatGPT when calling 2 function on submit button
            // we removed the event.preventDefault don't use this code in other project.
            event.preventDefault()
        }else{
            event.currentTarget.submit()
        }  
    }

As you can see later on i removed the **event.preventDefault()** so the form could submit because i handled form handling using another function as am going to display later on below after showing you the original email.js code.

Original **email.js** code file before putting it under one onclick.
// // Send Email      
  function sendMail() {
    var params = {
      name: document.getElementById("name").value,
      email: document.getElementById("email").value,
      message: document.getElementById("message").value,
    };
  
    const serviceID = "service_0vlh0ul";
    const templateID = "template_9n4gyyb";
  
      emailjs.send(serviceID, templateID, params)
      .then(res=>{
          document.getElementById("name").value = "";
          document.getElementById("email").value = "";
          document.getElementById("message").value = "";
          console.log(res);
          alert("Your message sent successfully!!")
  
      })
      .catch(err=>console.log(err));
  
  }

So as already posted above I said i combined the validate.js file and email.js file putting the code inside the validate.js file as currently looking below: This is my current running code as of now:

Combined validate.js and email.js code.
function printError(elemId, hintMsg){
    document.getElementById(elemId).innerHTML = hintMsg;
}

function contactUs(){ 
    var name = document.mydata.name.value;
    var email = document.mydata.email.value;
    var message = document.mydata.message.value;
    
    // ___ Defining error variables with default value
    var name_err = email_err = message_err = true;

    // _______ validating Name
    if(name === ""){
        printError("name_err", "Please Enter Your Name");
        const errId = document.getElementById('name');
        errId.style.border = '1px solid red';
    }
    else  if(name.length < 5 || name.length > 50){
        printError("name_err", "Names should be between 5-50 characters");
        const errId = document.getElementById('name');
        errId.style.border = '1px solid red';
    }
    else{
        var regex = /^[a-zA-Z\s]+$/;
        if(regex.test(name) === false){
            printError("name_err", "Names should not include numeral characters.");
            const errId = document.getElementById('name');
            errId.style.border = '1px solid red';
        }else{
            var uppercase = /^[A-Z][a-z]* [A-Z][a-z]*/;
            if(uppercase.test(name) === false){
            printError("name_err", "First letter of Name should be In Uppercase i.e Phil Ubuntu");
            const errId = document.getElementById('name');
            errId.style.border = '1px solid red';
        }else{
            printError("name_err", "");
            name_err = false;
        }
        }
    }

    // _______ validating Email Info
    if(email === ""){
        printError("email_err", "Email cannot be left Empty");
        const errId = document.getElementById('email');
        errId.style.border = '1px solid red';
    }else{
        var letters = /^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;;
        if(letters.test(email) === false){
            printError("email_err", "Invalid Email(Include @)")
            const errId = document.getElementById('email');
            errId.style.border = '1px solid red';
        }else{
            printError("email_err", "");
            email_err = false;
        }
    }

    // _______ validating message
    if(message === ""){
        printError("message_err", "Please Enter Your Message");
        const errId = document.getElementById('message');
        errId.style.border = '1px solid red';
        }    else{
            var uppercase = /^[A-Z][a-z]*/;
            if(uppercase.test(message) === false){
                printError("message_err", "First letter Should be In CapsLock e.g This is..");
                const errId = document.getElementById('message');
                errId.style.border = '1px solid red';
            }else{
            printError("message_err", "");
            message_err = false;
        }
    }

    // // __Preventing the form from being submited if their are any errors
    // if(( name_err || email_err || message_err) === true){
    //     // Temporary removing this as suggested by ChatGPT when calling 2 function on submit button
    //     // we removed the event.preventDefault don't use this code in other project.
    //     // event.preventDefault()
    // }else{
    //     event.currentTarget.submit()
    // }  
}

    // Send Email      
    function sendMail() {
        var params = {
          name: document.getElementById("name").value,
          email: document.getElementById("email").value,
          message: document.getElementById("message").value,
        };
      
        const serviceID = "service_0vlh0ul";
        const templateID = "template_9n4gyyb";
      
          emailjs.send(serviceID, templateID, params)
          .then(res=>{
              document.getElementById("name").value = "";
              document.getElementById("email").value = "";
              document.getElementById("message").value = "";
              console.log(res);
              alert("Your message sent successfully!!")
      
          })
          .catch(err=>console.log(err));
      }

    // async function sendMail() {
    //     var params = {
    //       name: document.getElementById("name").value,
    //       email: document.getElementById("email").value,
    //       message: document.getElementById("message").value,
    //     };
      
    //     const serviceID = "service_0vlh0ul"; // Replace with your EmailJS service ID
    //     const templateID = "template_9n4gyyb"; // Replace with your EmailJS template ID
      
    //     try {
    //       const result = await emailjs.send(serviceID, templateID, params);
    //       console.log(result);
    //       alert("Your message sent successfully!!");
    //       // Clear the form fields after successful submission
    //       document.getElementById("name").value = "";
    //       document.getElementById("email").value = "";
    //       document.getElementById("message").value = "";
    //     } catch (error) {
    //       console.error("Error sending email:", error);
    //     }
    //   }

      function submitForm() {
        // Call contactUs() first to perform validation
        contactUs();

          // Prevent the default form submission
        event.preventDefault();
      
        // Check if the validation was successful before proceeding with sending email
        if (!name_err && !email_err && !message_err) {
          // If validation passes, call the sendMail() function to submit the form data via emailJS
          sendMail();
        } else {
          // If there are validation errors, do nothing. The form will not submit.
        }
      }

正如我之前所说,当我从这里删除 event.preventDefault() 并在处理表单处理时更新它时,我将在此之后粘贴代码。

// // __Preventing the form from being submited if their are any errors
// if(( name_err || email_err || message_err) === true){
//     // Temporary removing this as suggested by ChatGPT when calling 2 function on submit button
//     // we removed the event.preventDefault don't use this code in other project.
//     // event.preventDefault()
// }else{
//     event.currentTarget.submit()
// }  

我在 submitForm() 函数中使用了 event.preventDefault(),如下所示,因为这正在处理表单提交。

  function submitForm() {
    // Call contactUs() first to perform validation
    contactUs();

      // Prevent the default form submission
    event.preventDefault();
  
    // Check if the validation was successful before proceeding with sending email
    if (!name_err && !email_err && !message_err) {
      // If validation passes, call the sendMail() function to submit the form data via emailJS
      sendMail();
    } else {
      // If there are validation errors, do nothing. The form will not submit.
    }
  }

现在我将向您展示我当前的 index.html 代码文件,请确保滚动到下面,以便您可以找到联系部分,因为投资组合网站的所有页面都在 index.js 文件中。 由于 StackOverflow 限制为 30000 个字符,我已经删除了索引 .html 文件,希望这会有所帮助

JavaScript HTML 表单 电子邮件 onclick

评论


答: 暂无答案