user5702166
user5702166

Reputation:

What is the right syntax for injecting Javascript with PhantomJS?

My goal is to inject:

javascript document.getElementById("pickupZip").value = "90049";
document.getElementById("refreshStoresForZipPop").click();

into a website with PhantomJS. This is all of the code on my inject.js file, and I get this in the console: SyntaxError: Expected an identifier but found "document" instead, so I know it is the wrong syntax, though I can't find a place that shows what the correct is. Here is my code for the PhantomJS file:

var webPage = require('webpage');
var page = webPage.create();

page.open('http://shop.advanceautoparts.com/p/purolator-classic-air-filter-a24278/5792304-P?navigationPath=L1*14934/', function(status) {
    var success = phantom.injectJs('inject.js');
    console.log(success);
    if (status === "success") {                   
      page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', function() {
            page.render('advanceautoparts.png');
            phantom.exit();
        });
    }
});

Upvotes: 1

Views: 474

Answers (1)

sudipto
sudipto

Reputation: 2482

Use evaluate.

var webPage = require('webpage');
var page = webPage.create();

page.open('http://shop.advanceautoparts.com/p/purolator-classic-air-filter-a24278/5792304-P?navigationPath=L1*14934/', function(status) {
    var success = phantom.injectJs('inject.js');
    console.log(success);
    if (status === "success") {                   
       page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js', function() {
            page.evaluate(function(s) {

                document.getElementById("pickupZip").value = "90049";
                document.getElementById("refreshStoresForZipPop").click();

              });
            page.render('advanceautoparts.png');
            phantom.exit();
        });
    }
});

Reference: http://phantomjs.org/api/webpage/method/evaluate.html

Upvotes: 1

Related Questions