Reputation: 5596
I am using Phantomjs. I need to pass certain information to the webpage (http://localhost:4569/index.html
) we are targeting. The idea is, as soon as the target page loads, pass a JSON object to page & set it a globally accessible variable. Something like window.data = {....}
. Once this variable is set, the target page will make use of this variable. Is it possible to get the desired result using 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);
//
Upvotes: 0
Views: 272
Reputation: 26920
One way that you might be able to facilitate this is a combination of setInterval
and injectJs()
. I would check for the data in the target page every few seconds. Then I would inject in a piece of data using injectJs
. Then I would digest the injected data and have the phantomjs script react accordingly.
<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>
/*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");
}
});
/*jslint browser:true devel:true*/
console.log("I'm from Phantom");
window.myVar = "I'm myVar!";
Upvotes: 1