Search code examples
javascriptphantomjsreferenceerror

PhantomJS: call a user defined/custom function within phantomjs


i'm getting a ReferenceError when i call a function i defined myself inside the page.evaluate() of Phantom; what is the proper way to do that ?

for example:

function mySweetFunction(item) {
    // process item....

}

page.evaluate(function(){

    var item= document.getElementsById('item');

    mySweetFunction(item);

});

then i'll get the error:

ReferenceError: Can't find variable: mySweetFunction

What is the proper way to do this ?

mySweetFunction is quite big, and i would prefer to keep it out of page.evaluate(...) if possible.


Solution

  • If you want to use a function inside page.evaluate() you have to put it there first:

    page.evaluate(function(){
    
        function mySweetFunction(item) {
            // process item....
        }
    
        var item = document.getElementsById('item');
    
        mySweetFunction(item);
    
    });