I'd like to intercept the submission of a form on a particular website. The form has no ID, but it does have a name. I'd prefer not to use jQuery, as my extension is very light weight and has no dependencies. The form is not submitted by a button, but by the submit() method.
I thought I could just handle the onSubmit event, but it doesn't seem to get raised.
Now I'm stumped, any ideas?
I'd like to intercept the submission of a form on a particular website. The form has no ID, but it does have a name. I'd prefer not to use jQuery, as my extension is very light weight and has no dependencies. The form is not submitted by a button, but by the submit() method.
I thought I could just handle the onSubmit event, but it doesn't seem to get raised.
Now I'm stumped, any ideas?
document.querySelector
and document.querySelectorAll
are for you
– noob
Commented
Dec 12, 2011 at 5:48
You can catch your form with
var myForm = document.getElementsByName('myForm');
Which returns a nodeList
(similar to Array
). Then you can override the submit
event in two ways:
myForm.onsubmit = function (evt) {...};
or
myForm.addEventListener('submit', function (evt) {...});
Be careful to only use lowercase letters for the event name. With the second example you can bind multiple listeners to the event but it isn't supported by older browsers (< IE 9).
Example:
html:
<form name="myForm" action="#" method="post">
<input type="submit" value="Send">
</form>
js:
var myForm;
myForm = document.getElementsByName('myForm')[0];
myForm.onsubmit = function (evt) {
// Do things here before passing on or stop the submit
};
In my content.html:
var patch = document.createElement('script');
patch.src= chrome.extension.getURL('patch.js')
document.body.appendChild(patch);
document.forms['logoutForm'].onsubmit = function() {
chrome.extension.sendRequest({logout: true});
}
In patch.js:
document.logoutForm.submitOrig = document.logoutForm.submit;
document.logoutForm.submit = function() {
this.onsubmit();
this.submitOrig();
};
You can use query selector for each element. For example, if you have a textarea and form, you can access to the form data like this below.
<form class="my-form">
<textarea
id="myTextArea"
/>
<button
type="submit"
class="my-button"
id="myButton">
Button
</button>
</form>
const myButton = document.querySelector("#myButton")
myButton.addEventListener("click", async() => {
const form = document.querySelector("form.my-form")
const textarea = document.querySelector("#myTextArea")
})