botfront / rasa-webchat

A feature-rich chat widget for Rasa and Botfront
https://botfront.io/rasa
Apache License 2.0
947 stars 495 forks source link

pressing enter to send a message causes a redirect #307

Open laurencejennings opened 3 years ago

laurencejennings commented 3 years ago

I'm using webchat with a rasa server and a mern application.

Everything is working fine but on firefox if I press enter to send my message, instead of sending the message I get redirected to http://localhost:3000/?message=yes

After this, probably because of my react routes, the browser returns to the previous location, http://localhost:3000/, and the chat is in the state it was before pressing enter to send the message.

Clicking on the send button of the chat widget however works correctly. Also, on chrome this behavior is not happening.

MarcelWepper commented 3 years ago

It seems like that FF's default behavior when a form is submitted that the page gets refreshed. By prohibiting this, this behavior does not happen anymore. Following code can be used to implement such logic:

   const findFormTimeoutRef = React.useRef<any>();

  const injectSubmit = () => {
    const form = document.querySelector(".rw-sender");

    if (form) {
      // Following code stops the form
      // from submitting before .click is called
      form.addEventListener("submit", function (e) {
        e.preventDefault();
      });
    } else {
      if (findFormTimeoutRef.current) {
        clearTimeout(findFormTimeoutRef.current);
      }
      findFormTimeoutRef.current = setTimeout(injectSubmit, 100);
    }
  };

  React.useEffect(() => {
    injectSubmit();
  }, []);
kabirivan commented 2 years ago

You can use this snipped of code:

import React from "react";
import Widget from "rasa-webchat";

const Chatbot: React.FC<{
}> = ({ }) => {

  // Bugfix in order to get the Enter Key working
  const handleKeyDown = (event: any) => {
    if (event.key === "Enter") {
      try {
        // @ts-ignore
        // eslint-disable-next-line
        document.querySelector(".rw-send").click();
      } catch (e) {
        console.log(e);
      }
    }
  };

  return (
    <div onKeyDown={handleKeyDown}>
        <Widget
          socketUrl={"URL"}
          socketPath={"/socket.io/"}
          title={"KeyFix"}
          initPayload={get_Started}
          params={{ storage: "session" }}
        />
    </div>
  );
};

export default Chatbot;