使用PhantomJS注入Javascript的正确语法是什么?

时间:2016-07-05 20:31:00

标签: javascript phantomjs javascript-injection

我的目标是注入:

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

进入PhantomJS的网站。这是我的inject.js文件中的所有代码,我在控制台中得到了这个:SyntaxError: Expected an identifier but found "document" instead,所以我知道这是错误的语法,虽然我找不到一个显示内容的地方是的。这是我的PhantomJS文件的代码:



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();
        });
    }
});




1 个答案:

答案 0 :(得分:1)

使用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();
        });
    }
});

参考:http://phantomjs.org/api/webpage/method/evaluate.html