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 doExamples
You may need a generic function to get the
checked
property from a checkbox. CasperJS currently only providesgetElementAttribute
function which will not work in this case.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 eachli
element then you have at least 2 possibilities to retrieve the uids.Casper-only:
Casper-Evaluate:
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:
Change site appearance through CSS:
Roots
CasperJS is built on top of PhantomJS and as such inherits some of its quirks. The PhantomJS documentation for
page.evaluate()
says this: