TheRifler
TheRifler

Reputation: 51

CasperJS inject javascript via this.evaluate

Today I tried to inject some javascript logic into remote page using CasperJS with PhantomJS together.

Well, I'm quite surprised because of that:

casper.then(function() {
    console.log(this.evaluate(function() {
        function myMethod() {
            return 'Any thing?!';
        }
        return myMethod();
    }));
    console.log(this.evaluate(function() {
        return myMethod();
    }));
});

I tried many combinations... Like:

casper.evaluate(...)
this.evaluate(...)
casper.page.evaluate(...) <- directly to phantomJS
this.page.evaluate(...)   <- as above

First case gives me exactly what I want. But next call to evaluate act as an idiot, which never saw executed code above.

I just want to change variables, functions, and other over remote site js runtime.

Can anybody tell me why this is happening? Greetings.

Upvotes: 1

Views: 2241

Answers (1)

Ruan Mendes
Ruan Mendes

Reputation: 92314

You cannot do what you are thinking. myMethod is private to the function that is passed to this.evaluate. It doesn't make sense that you would expect a private function to be available in another function, just because it was passed to the same method.

In your example, you could try

casper.then(function() {
    function myMethod() {
        return 'Any thing?!';
    }
    console.log(this.evaluate(function() {
        return myMethod();
    }));
    console.log(this.evaluate(function() {
        return myMethod();
    }));
});

But that is probably not what you are looking for? Or is it?

Or are you trying to attach code to the page itself? Maybe the following?

casper.then(function() {
    console.log(this.evaluate(function() {
        // Just creating a variable won't attach it to the window, it will
        // be local to the function. However, you can attach it to the window
        // object, which is in the scope chain
        window.myMethod = function () {return 'anything'};
    }));
    console.log(this.evaluate(function() {
        return myMethod(); // or window.myMethod();
    }));
});

Upvotes: 5

Related Questions