0

The following form requires a cookie called IMPORTANT_COOKIE to be present in order to be submitted. The cookie presence is being checked when the user is submitting the form. Everything is fine as long as the user does it by clicking Submit button, but the test is totally ignored when submitted with the code (as with the link below). How to be 100% sure to cover all means of form submission?

<form action="javascript:alert('FORM FIRED');" method="post" id='form1'>
    <input type="text" name="something" value="something">
    <input type="submit">
</form>
<a href="javascript:document.getElementById('form1').submit();">Bypass important cookie test</a>

<script>
    function callback(e) {
      e.preventDefault(); 
      return waitForCookie().then(cookie => {
          return this.submit();
        });
    }
    function waitForCookie() {
      return new Promise(function (resolve, reject) {
        var intervalID = setInterval(checkForCookie, 1000);
        function checkForCookie() {
          var cookie = getCookie();
          if (cookie) {
            clearInterval(intervalID);
            resolve(cookie);
          }
        }
      });
    }
    function getCookie() {
      if (document.cookie.indexOf('IMPORTANT_COOKIE') == -1) {
        console.log("No cookie found - sorry")
        return undefined;
      } else {
        console.log("Hurray! Cookie found - proceeding")
        return 'cookie!';
      }
    }
    document.getElementById('form1').addEventListener("submit", callback, false);
</script>
Mike
  • 11
  • 2

2 Answers2

0

When you submit a form from script your event listener is not called.

A solution to your problem could be:

<a href="javascript:callback.bind(document.getElementById('form1')());">Bypass
HMR
  • 37,593
  • 24
  • 91
  • 160
0

I figured it out :) Hopefully someone will have some time saved in the future :)

form = document.getElementById('form1')
tmp_submit = form.submit
form.submit = function(e) {
    return waitForCookie().then(cookie => {
        tmp_submit.apply(form)
    });
}
Mike
  • 11
  • 2