How to execute Javascript in headless chrome using php-phantomjs?

2k Views Asked by At

I'm trying to run a headless browser and run JS scripts (a bot) within it using but want to run it using php. Searching on Google, I found a implementation / wrapper of PhantomJS as php-phantomjs. Please bear with me, I'm very new to this stuff.

Here what I'm trying to do is to take screenshot of alert window (this is not necessary, but just to test if JS is executed and then the screenshot is taken.)

Here is my code:

// file: app.php

$client = PhantomJsClient::getInstance();
$client->isLazy();

$location = APP_PATH . '/partials/';

$serviceContainer = ServiceContainer::getInstance();
$procedureLoader = $serviceContainer->get('procedure_loader_factory')->createProcedureLoader($location);

$client->getProcedureLoader()->addLoader($procedureLoader);

$request  = $client->getMessageFactory()->createCaptureRequest();
$response = $client->getMessageFactory()->createResponse();

$request->setViewportSize(1366, 768);
$request->setHeaders([
    'User-Agent' => 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36'
]);

$request->setTimeout(5000);
$request->setUrl('https://www.google.co.in');

$request->setOutputFile(APP_PATH . '/screen.jpg');

$client->send($request, $response);

Tried two custom scripts as given in the list here: http://jonnnnyw.github.io/php-phantomjs/4.0/4-custom-scripts/

// file: page_on_resource_received.partial, page_open.partial

alert("Hello");

OUTPUT: It just shows the page, not the alert window.

I repeat, Its not about taking screenshot, that's just to be sure that JS is executing. I just want to execute my JS scripts (better say bots) like:

var form = document.getElementById('form');
var event = new Event('submit');
form.dispatchEvent(event);

or maybe using jQuery and then return the output of that page to php as response or so. So, if there is any other way to run bots using php in a headless browser please mention that in your answers or comments.

1

There are 1 best solutions below

3
Vaviloff On

PhantomJS is headless, that is it doesn't have GUI. Therefore no window dialogs can be seen.

Try writing custom text to an element instead of alert, like

document.getElementById("#title").innerHTML = "It works!";