Skip to content

Commit d9c8cea

Browse files
committed
added run time binding on form submit
rather than attaching the addEventListener on form, set it on body to be able to bind to forms. Thus supporting the dynamically added contents like dynamically added forms.
1 parent cdf167d commit d9c8cea

File tree

1 file changed

+24
-12
lines changed

1 file changed

+24
-12
lines changed

js/csrfprotector.js

Lines changed: 24 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -171,23 +171,35 @@ function csrfprotector_init() {
171171

172172
// Call the init funcion
173173
CSRFP._init();
174-
174+
175+
// definition of basic FORM submit event handler to intercept the form request
176+
// and attach a CSRFP TOKEN if it's not already available
177+
var BasicSubmitInterceptor = function(event) {
178+
if (typeof event.target[CSRFP.CSRFP_TOKEN] === 'undefined') {
179+
event.target.appendChild(CSRFP._getInputElt());
180+
} else {
181+
//modify token to latest value
182+
event.target[CSRFP.CSRFP_TOKEN].value = CSRFP._getAuthKey();
183+
}
184+
}
185+
175186
//==================================================================
176187
// Adding csrftoken to request resulting from <form> submissions
177188
// Add for each POST, while for mentioned GET request
178189
// TODO - check for method
179190
//==================================================================
180-
for(var i = 0; i < document.forms.length; i++) {
181-
document.forms[i].addEventListener("submit", function(event) {
182-
if (typeof event.target[CSRFP.CSRFP_TOKEN] === 'undefined') {
183-
event.target.appendChild(CSRFP._getInputElt());
184-
} else {
185-
//modify token to latest value
186-
event.target[CSRFP.CSRFP_TOKEN].value = CSRFP._getAuthKey();
187-
}
188-
});
189-
}
190-
191+
// run time binding
192+
document.querySelector('body').addEventListener('submit', function() {
193+
if (event.target.tagName.toLowerCase() === 'form') {
194+
BasicSubmitInterceptor(event);
195+
};
196+
});
197+
198+
// intial binding
199+
// for(var i = 0; i < document.forms.length; i++) {
200+
// document.forms[i].addEventListener("submit", BasicSubmitInterceptor);
201+
// }
202+
191203
//==================================================================
192204
// Adding csrftoken to request resulting from direct form.submit() call
193205
// Add for each POST, while for mentioned GET request

0 commit comments

Comments
 (0)