Is there a way to pass a casper.js' evaluation () object?

I saw this thread and it looks like there is no way to pass a complex evaluate() object https://groups.google.com/forum/#!topic/casperjs/x7I8LDFwFJ0

So, if I write an object and want to share between different evaluate() , how to do it?

Say, for example, such a stupid object where I want to use the getData function again and again:

 var testObj = (function() { var a = 1; function test1(b) { return (a+b); } return { getData : function(arg) { return (test1(3) + arg); } } })(); 

Is there a workaround?

UPDATE 1:

I want to pass an object with functions. As below, but it does not work (return null ):

 var casper = require('casper').create(); casper.start('about:blank', function() { var TestObj = function() { var a = 1; function test1(b) { return (a+b); } return { getData : function(arg) { return (test1(3) + arg); } } } var testObj = new TestObj(); this.echo(casper.evaluate(function(myObject ) { return myObject.getData(100); }, testObj)); }); casper.run(function() { this.exit(); }); 
+4
source share
2 answers

Unfortunately, you cannot pass a complex structure to evaluate (), because any argument passed to evaluate () is of the form JSON.parse (JSON.stringify (arg)).

But this does not mean that you cannot transfer objects of another type.

An example of how to pass a JSON object for evaluation.

 var casper = require('casper').create(); casper.start('about:blank', function() { var JSONObject = { arg1: 'val1' , arg2: 'val2' }; this.echo(casper.evaluate(function(myObject ) { return JSON.stringify(myObject); }, JSONObject)); }); casper.run(function() { this.exit(); }); 

An example of how to pass a base object for evaluation.

 var casper = require('casper').create(); casper.start('about:blank', function() { obj = new Object(); obj.param1 = "value1"; obj.param2 = "value2"; this.echo(casper.evaluate(function(myObject ) { return JSON.stringify(myObject); }, obj)); }); casper.run(function() { this.exit(); }); 

An example of how to pass a function with parameters for evaluation.

 var casper = require('casper').create(); casper.start('about:blank', function() { var arg1 = "value1"; var arg2 = "value2"; this.echo(casper.evaluate(myFunction, arg1, arg2)); }); casper.run(function() { this.exit(); }); function myFunction(arg1, arg2) { return arg1 + "-" + arg2; } 
+14
source

You can use the clientScripts parameter to pass on scripts like jQuery - Can jQuery be used with CasperJS . Perhaps you could do the same for custom scripts and have good code separation.

 var casper = require('casper').create({ clientScripts: ["includes/jquery.min.js", "lib/my-custom-script.js"] }); casper.start(function () { this.evaluate(function () { window.customFunction(); }); }); 

Library / My-customs-scripts.js:

 window.customFunction = function () { /* do stuff */ }; 

Hope this helps.

+2
source

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


All Articles