RavenHursT
RavenHursT

Reputation: 2344

Having trouble getting page.injectJs() to work in PhantomJS

I have the following in my code:

phantom.createPage(function(page){
    page.onCallback = function(data) {
        console.log("ph callback: ", data);
    };
    page.open(req.query.testUrl, function(status){
        if(status !== 'success'){
            page.close();
            res.status(500)
                .send('Page "' + testUrl + '" could not be loaded.')
                .end();
            return;
        }

        var result = page.injectJs('lib/my-test-script.js');
        console.log('injectJS: ', result);

        page.evaluate(function(){
            window.callPhantom(window.mocha.constructor.name);
        }, function(){
            console.log('finished');
            page.close();

            res.json({status: status});
            res.end();
        });
    });
});

And console.log('injectJS: ', result); is outputting "injectJS: undefined", not explicitly false as the docs say here:

http://phantomjs.org/api/webpage/method/inject-js.html

Furthermore, I've verified that my-test-script.js is there using fs.readDir(), yet it appears that my code isn't being injected at all, not to mention, I never get the console output from page.onCallback().

I'm completely lost at this point. I'm obviously doing something wrong, but I'm clueless as to what it could be. Any help would be appreciated.

Associated GitHub Issue.

Upvotes: 1

Views: 544

Answers (1)

Artjom B.
Artjom B.

Reputation: 61892

You're using a bridge between node.js and PhantomJS (probably phantomjs-node) so the PhantomJS docs don't apply directly.

All bridged functions (basically all PhantomJS functions) take an additional callback if they don't already to so. This is described under Functionality details in the bridge docs. The same is true for injectJs. Also, the way you register to events is also different:

page.set("onCallback", function(data) {
    console.log("ph callback: ", data);
});
...
page.injectJs('lib/my-test-script.js', function(){
    page.evaluate(function(){
        window.callPhantom(window.mocha.constructor.name);
    }, function(){
        console.log('finished');
        page.close();

        res.json({status: status});
        res.end();
    });
});

Upvotes: 2

Related Questions