Search code examples
javascriptgoogle-chromegoogle-chrome-devtools

Prevent form submission leading to redirect while debugging


I was not sure which tags to add here.

I'm adding some tracking to formSubmit events in Javascript. I would like to experiment by submitting the form several times in my browser and wondered if theres some setting in Chrome or some JS I can type in the console that would prevent the form redirecting when I submit it?


Solution

  • If you have jQuery on your page, and your form has an ID, you could run this in your console before debugging:

    $("#formId").submit(function(e){ e.preventDefault(); });
    

    This can be done more verbosely without either condition as:

    document.getElementsByTagName("form")[0].onsubmit = function(e) {
      e.preventDefault();
    };
    

    The second assumes the form in question is the first form on your page. The index may need to be adjusted.

    For all forms with jQuery:

    $("form").submit(function(e){ e.preventDefault(); });
    

    Or without jQuery:

    Array.from(document.getElementsByTagName("form")).forEach(
      (form) => {
        form.onsubmit = function(e) { e.preventDefault(); };
      });
    

    Note - the function is called through the Array prototype because document.getElementsByTagName returns an HTMLCollection rather than an Array.

    For the two without jQuery, you may run into issues if you are trying to test a submit handler that you have already bound to your form. If that is the case, replace

    form.onsubmit = function(e) { e.preventDefault(); };
    

    with this:

    form.addEventListener("submit", function(e) {
      e.preventDefault();
    });
    

    It is slightly longer, but won't overwrite any existing event handlers bound to the form.