How to intercept a request made by a form submit in JavaScript?

32 Views Asked by At

I'd like to be able to intercept the request made by submitting an HTML form (form tag).

To achieve this, I've tried using service workers. This works well when the origin of the request doesn't change, but if it does, then the service worker fails to intercept the request.

My aim is to inject JavaScript code into a web page (that I don't control), and to be able to hook/intercept the request issued by a form submission, even if the origin of the request differs from the origin of the web page.

For example, here's the code for a simple form:

  <form action="https://unknoworigin.com/index.html" method="POST">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required><br><br>

    <label for="message">Message:</label><br>
    <textarea id="message" name="message" rows="4" cols="50" required></textarea><br><br>

    <button type="submit">Send</button>
  </form>

Here is the code for my service worker:

self.addEventListener('fetch', (event) => {
    console.log('Service worker, event for:', event.request.url);

    event.respondWith(fetch(event.request));
});

I'd like to find a technique to intercept any request from a form submission.

0

There are 0 best solutions below