Ethan
Ethan

Reputation: 2087

How to pass a dynamic JS file into PhantomJS

I am trying to take the value of am input, use AJax to submit these variables into a php function, call PhantomJS from said PHP function WITH these arguments passed from AJax, and return the result back to the HTML page. I am passing the variables to the PHP file perfectly fine, the problem arises from calling PhantomJS with my script followed by the three arguments.

This is the script on my PHP page to call PhantomJS

echo json_encode(array("abc" => shell_exec('/Applications/XAMPP/htdocs/scripts/phantom/bin/phantomjs /Applications/XAMPP/htdocs/scripts/phantom/examples/test.js 2>&1',$website)));

This is the script referenced in the shell script:

var args = require('system').args;
args.forEach(function(arg, i) {

    console.log(i+'::'+arg);

});
var page = require('webpage').create();
var address = args[1];
page.open(address, function () {
    console.log("Done")
}); 

As you can see it should be a relatively simple process, except nothing at all is being echo'd. Permissions for each file are more than adequate, and I am sure these files are executing because if I change the shell script to run hello.jsEverything echo's and logs perfectly.

ALSO NOTE This script is executing on my web server, so I am not 100% certain there IS a system variable.

Any ideas?

Upvotes: 1

Views: 179

Answers (1)

MerlinTheMagic
MerlinTheMagic

Reputation: 605

First issue, shell_exec() takes a single argument (Documentation). However your example is passing the shell argument ($website) as a second argument on shell_exec().

Corrected Example:

$shellReturn = shell_exec("/Applications/XAMPP/htdocs/scripts/phantom/bin/phantomjs /Applications/XAMPP/htdocs/scripts/phantom/examples/test.js " . $website);
echo json_encode(array("abc" => $shellReturn));

For simplicity i excluded the redirect of the error pipe. In addition i would suggest you pass the arguments as JSON wrapped in base64 encoding. This eliminates URL spacing resulting in multiple arguments. Once PhantomJS receives the system args use atob() to bring the JSON back and iterate over the JSON obj rather than the raw string arguments.

I would also point you towards this project: https://github.com/merlinthemagic/MTS, Under the hood is an instance of PhantomJS, the project just wraps the functionality of PhantomJS.

$myUrl          = "http://www.example.com"; //replace with content of your $website variable 
$windowObj      = \MTS\Factories::getDevices()->getLocalHost()->getBrowser('phantomjs')->getNewWindow($myUrl);

//if you want the DOM or maybe screenshot and any point run:
$dom       = $windowObj->getDom();
$imageData = $windowObj->screenshot();

Upvotes: 1

Related Questions