There is an easier way than the one below. You can access the casper.page.customHeaders
property of PhantomJS' Webpage instance.
casper.then(function() {
casper.page.customHeaders = {
"CuStOm": "Header"
}; // set headers
this.fillSelectors("#registration-form", { /*...*/ }, true);
});
casper.then(function() {
casper.page.customHeaders = {}; // reset headers
});
The problem is that this method will add your custom header to every request until you disable it again. You can experiment with resetting headers based on setTimeout
or directly behind fillSelectors
.
You cannot set headers for a form submission in the browser. __utils__.sendAJAX
also doesn't provide custom headers.
You will need to use XMLHttpRequest to send the request. The following function replaces the submit handler of the form to send the Ajax call and also waits:
casper.thenFormToXHR = function(formSelector, data, customHeaders){
this.thenEvaluate(function(formSelector, customHeaders){
// see https://stackoverflow.com/a/19838177/1816580
function submitForm(oFormElement) {
window.__requestDone = false;
var xhr = new XMLHttpRequest();
for(var header in customHeaders) {
xhr.setRequestHeader(header, customHeaders[header]);
}
xhr.onload = function(){
window.__requestDone = true;
};
xhr.open (oFormElement.method, oFormElement.action, true);
xhr.send (new FormData(oFormElement));
return false;
}
document.querySelector(formSelector).onsubmit = submitForm;
}, formSelector, customHeaders);
this.then(function(){
this.fillSelectors(formSelector, data, true);
});
this.waitFor(function check(){
return this.evaluate(function(){
return window.__requestDone;
});
});
};
You can then invoke like this:
casper.thenFormToXHR("#registration-form", {
"#first-name": "Bob",
"#last-name": "Smith",
"#email-address": RANDOM_EMAIL,
"#password": PASSWORD,
"#password-confirm": PASSWORD
}, {
"X-Requested-With": "XMLHttpRequest" // here should be your custom headers
});
The code can be reduced, if you don't need to wait for the XHR completion:
casper.formToXHR = function(formSelector, data, customHeaders){
this.evaluate(function(formSelector, customHeaders){
// see https://stackoverflow.com/a/19838177/1816580
function submitForm(oFormElement) {
var xhr = new XMLHttpRequest();
for(var header in customHeaders) {
xhr.setRequestHeader(header, customHeaders[header]);
}
xhr.open (oFormElement.method, oFormElement.action, true);
xhr.send (new FormData(oFormElement));
return false;
}
document.querySelector(formSelector).onsubmit = submitForm;
}, formSelector, customHeaders);
this.fillSelectors(formSelector, data, true);
};