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?
Share Improve this question edited Mar 23, 2014 at 9:53 Flexo - Save the data dump♦ 88.9k22 gold badges201 silver badges281 bronze badges asked Dec 12, 2011 at 5:46 kwertykwerty 431 silver badge5 bronze badges 1-
document.querySelector
anddocument.querySelectorAll
are for you – noob Commented Dec 12, 2011 at 5:48
3 Answers
Reset to default 5You 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.
HTML
<form class="my-form">
<textarea
id="myTextArea"
/>
<button
type="submit"
class="my-button"
id="myButton">
Button
</button>
</form>
JS
const myButton = document.querySelector("#myButton")
myButton.addEventListener("click", async() => {
const form = document.querySelector("form.my-form")
const textarea = document.querySelector("#myTextArea")
})