Understanding Evaluation Function in CasperJS

I want to understand in which case I need or need to use a function evaluate.

I read an API document about a function evaluatefor CasperJS, but I'm not sure when I should use this function. And what does the DOM context mean? Can someone give an example?

+4
source share
1 answer

The CasperJS documentation has a pretty good description of what it does casper.evaluate().

Recall: you pass a function that will be executed in the context of the DOM (you can also call it the context of the page). You can pass some primitives as arguments to this function and return one primitive back. Keep in mind that this function that you pass on evaluatemust be autonomous. It cannot use variables or functions defined outside this function.


CasperJS provides many good features for everyday tasks, but you may run into a situation where you need a custom function for something. evaluatemostly there

  • Retrieve some value from the page to take action based on this in the script
  • Manipulate the page in any way other than clicking or filling out the form
  • Combinations of points 1. and 2.

Examples

, checked . CasperJS getElementAttribute, .

function getChecked(cssSelector){
    return document.querySelector(cssSelector).checked;
}

if (casper.evaluate(getChecked, selector)){
    // do something
} else {
    // do something else
}

, . data-uid li, 2 uids.

Casper-:

var uids = casper.getElementsAttribute('ul#user-list > li', 'data-uid');

Casper-:

var uids = casper.evaluate(function(){
    return Array.prototype.map.call(document.querySelectorAll('ul#user-list > li'), function(li){ return li["data-uid"]});
});

, , . , -, , . CSS .

:

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 :)

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 PhantomJS , , . PhantomJS page.evaluate() :

. evaluate . : JSON, .

, , DOM .. !

+11

Source: https://habr.com/ru/post/1544551/


All Articles