Intercepting a form submission in a Chrome content extension

穿精又带淫゛_ 提交于 2019-12-22 18:42:35

问题


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?


回答1:


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
};



回答2:


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();

};


来源:https://stackoverflow.com/questions/8470379/intercepting-a-form-submission-in-a-chrome-content-extension

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!