3

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.

Sukanta Paul
  • 784
  • 3
  • 19
  • 36

1 Answers1

0

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!";
Vaviloff
  • 16,282
  • 6
  • 48
  • 56
  • I tried using your code, but no change to output. Am I doing something wrong in the procedure? – Sukanta Paul Aug 02 '17 at 21:22
  • Dont use itas it is, there is no #title element on Google page. – Vaviloff Aug 03 '17 at 02:21
  • Yeah, I know. I tried modifying a little bit as per my need and tested on a custom html not on Google page. Can you please give me a snippet of your code you are using to accomplish this? – Sukanta Paul Aug 04 '17 at 17:33