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?
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();
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.