I want to understand in which case I should or have to use the evaluate
function.
I have read the API doc about the evaluate
function of CasperJS, but I'm unsure in which case I should use this function. And what does DOM context mean? Can somebody provide an example?
The CasperJS documentation has a pretty good description of what casper.evaluate()
does.
To recap: You pass a function that will be executed in the DOM context (you can also call it the page context). You can pass some primitives as arguments to this function and return one primitive back. Keep in mind that this function that you pass to evaluate
must be self contained. It cannot use variables or functions that are defined outside of this function.
CasperJS provides many good functions for everyday tasks, but you may run into a situation when you need a custom function to do something. evaluate
is basically there to do
You may need a generic function to get the checked
property from a checkbox. CasperJS currently only provides getElementAttribute
function which will not work in this case.
function getChecked(cssSelector){
return document.querySelector(cssSelector).checked;
}
if (casper.evaluate(getChecked, selector)){
// do something
} else {
// do something else
}
In most of the cases it is just preference of what you want to use. If you have a list of users with data-uid
on each li
element then you have at least 2 possibilities to retrieve the uids.
Casper-only:
var uids = casper.getElementsAttribute('ul#user-list > li', 'data-uid');
Casper-Evaluate:
var uids = casper.evaluate(function(){
return Array.prototype.map.call(document.querySelectorAll('ul#user-list > li'), function(li){ return li["data-uid"]});
});
Regarding manipulation everything is possible but depends on what you want to do. Let's say you want to take screenshots of web pages, but there are some elements that you don't want to be there. Or you could add your own CSS to the document.
Remove elements:
function removeSelector(cssSelector){
var elements = document.querySelectorAll(cssSelector);
Array.prototype.forEach.call(elements, function(el){
el.parent.removeChild(el);
});
}
casper.evaluate(removeSelector, '.ad'); // if it would be that easy :)
Change site appearance through CSS:
function applyCSS(yourCss){
var style = document.createElement("style");
style.innerHTML = yourCss;
document.head.appendChild(style);
}
casper.evaluate(applyCSS, 'body { background-color: black; }'); // non-sense
CasperJS is built on top of PhantomJS and as such inherits some of its quirks. The PhantomJS documentation for page.evaluate()
says this:
Note: The arguments and the return value to the
evaluate
function must be a simple primitive object. The rule of thumb: if it can be serialized via JSON, then it is fine.Closures, functions, DOM nodes, etc. will not work!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With