使用phantomjs将值传递给目标网页

时间:2016-06-22 18:39:01

标签: javascript phantomjs

我正在使用Phantomjs。我需要将某些信息传递到我们定位的网页(http://localhost:4569/index.html)。这个想法是,一旦目标页面加载,就将JSON对象传递给page&设置一个全局可访问的变量。像window.data = {....}这样的东西。设置此变量后,目标页面将使用此变量。是否可以使用Phantomjs获得所需的结果?

var webPage = require('webpage');
var page = webPage.create();
var settings = {
  operation: "POST",
  encoding: "utf8",
  headers: {
    "Content-Type": "application/json"
  },
  data: JSON.stringify({
    some: "data",
    another: ["custom", "data"]
  })
};

page.open('http://localhost:4569/index.html', settings, function(status) {
  console.log('Status: ' + status);
  //

1 个答案:

答案 0 :(得分:1)

您可以通过setIntervalinjectJs()的组合来实现这一目标。我会每隔几秒检查目标页面中的数据。然后我会使用injectJs注入一段数据。然后我会消化注入的数据并让phantomjs脚本做出相应的反应。

的index.html

<html>

<head>
    <title>Phantest</title>
</head>

<body>
    <main>
        <h1>Phantom Test</h1>
        <p>Test of phantom</p>
    </main>
    <script>
        (function () {
            console.log("Hello");
            setInterval(function () {
                if (window.myVar) {
                    console.log("window.myVar is here!");
                    console.log(window.myVar);
                }
            }, 1000);
        }());
    </script>
</body>

</html>

phan.js

/*jslint node:true*/

"use strict";

var page = require("webpage").create();

page.onConsoleMessage = function (msg) {
    console.log(msg);
};

page.open("http://127.0.0.1:52987/index.html", function (status) {
    if (status === "success") {
        page.injectJs("inject.js");
    }
});

inject.js

/*jslint browser:true devel:true*/
console.log("I'm from Phantom");

window.myVar = "I'm myVar!";