javascriptnode.jsphantomjscasperjsspookyjs

is it possible to call evaluation function from node scope in casperjs scope using spookyjs?


I try to pass to spooky an outside function, But when I call it, the returned value is 'undefined'. Here is my code:

        var eval_func = function(){
           return 123;
        };
        console.log('Outside spooky: ' + eval_func());
        var spooky = new Spooky({
            child: {
                transport: 'http',
            },
            casper: {
                logLevel: 'error',
            }
        }, function (err) {
            if (err) {
                e = new Error('Failed to initialize SpookyJS');
                e.details = err;
                throw e;
            }

            spooky.start('http://google.com/',[{
                eval_func:eval_func,
            },function(){
                console.log('Inside spooky: ' + eval_func());
            }]);
            spooky.run();
        });

        spooky.on('console', function (line) {
            console.log(line);
        });
    });

and the output is:

Outside spooky: 123

And I get "ReferenceError: Can't find variable: eval_func". Is it possible to do this without getting any ReferenceError?


Solution

  • OK, I found a good way to get around this. I copied the function string and then regenerated it in the casperjs scope.

            eval_func = function(){
                return 123;
            }
            console.log('Outside spooky: ' + eval_func());
            var spooky = new Spooky({
                child: {
                    transport: 'http',
                },
                casper: {
                    logLevel: 'error',
                }
            }, function (err) {
                if (err) {
                    e = new Error('Failed to initialize SpookyJS');
                    e.details = err;
                    throw e;
                }
                eval_func_str = eval_func.toString();
    
                spooky.start('http://google.com/',[{
                    eval_func_str:eval_func_str,
                },function(){
                    eval("eval_func=" + eval_func_str);
                    console.log('Inside spooky: ' + eval_func());
                }]);
    
                spooky.run();
            });
    
            spooky.on('console', function (line) {
                console.log(line);
            });