0

I'm trying to call a function defined in another module using this.evaluate().

The code snippet(calling the function) is:

this.waitFor(function check() {
    var re = this.evaluate(universe.answer(couponElement, url));
    if (re != 'no' & re!='yes' & re!=null) {
        couponObj.push(re);

and the module in which the function is defined is like this:

var require = patchRequire(require);

var utils = require('utils');
exports.answer = function(couponElement, url) {
    var lblInvalidCoupon = 'lblInvalidCoupon';
    var tolTipCouponinner='tolTipCouponinner';
    var txtFCCoupondisocunt = 'txtFCCoupondisocunt';
    var btnRemoveFCCoupon = 'btnRemoveFCCoupon';

    var check = $('#txtCouponCode').css('backgroundImage');
    if (check.indexOf('ajax-loader.gif')>-1){        
        return 'no';
    } else {
        if (document.getElementById(lblInvalidCoupon)!=null){

Basically, I want to call the function using this.evaluate but unable to do so.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
user2747776
  • 109
  • 1
  • 15
  • Have you checked to make sure that the remote page has jQuery loaded? You can do this by visiting the page in your browser and trying to use a jQuery function with the browser's developer tools. – hexid Sep 30 '13 at 16:14
  • possible duplicate of [In JavaScript, does it make a difference if I call a function with parentheses?](http://stackoverflow.com/questions/3246928/in-javascript-does-it-make-a-difference-if-i-call-a-function-with-parentheses) – Artjom B. Dec 10 '14 at 19:38

2 Answers2

0

First, try with the simplest evaluate: remote.message event to capture console.log from page.

casper.on("remote.message", function(msg) { 
    console.log("[page] " + msg); 
});

this.evaluate(function () { 
    console.log("Hi phantomworld! I am hello-ing from remote page!"); 
});

Next, check if jQuery is present:

this.evaluate(function () { 
    console.log(typeof jQuery); 
});

If it says, [page] function, jQuery is present in the page. You need to dig more...

If not, inject it:

var casper = require('casper').create({
    clientScripts:  [
        'includes/jquery.js'
    ]
});     
sudipto
  • 2,472
  • 1
  • 17
  • 21
-3

You didn't actually pass the answer function to casper.evaluate, but you called it instead. The problem is that in this way answer was not executed in page context and because of this $ is not defined. casper.evaluate which executes a function in page context is sandboxed. It cannot use variables which are defined outside. The passed function must be self contained.

To fix this the arguments which are consumed by answer can be passed as additional parameters to casper.evaluate.

Change the line

var re = this.evaluate(universe.answer(couponElement, url));

to

var re = this.evaluate(universe.answer, couponElement, url);

If JQuery is not present in the page you need to follow sudipto's answer.

Community
  • 1
  • 1
Artjom B.
  • 61,146
  • 24
  • 125
  • 222