Skip to content

Instantly share code, notes, and snippets.

@cookieguru
Created May 23, 2021 20:41
Show Gist options
  • Save cookieguru/bc2047dc46d4e88a8e57d73c2395d233 to your computer and use it in GitHub Desktop.
Save cookieguru/bc2047dc46d4e88a8e57d73c2395d233 to your computer and use it in GitHub Desktop.
AJAX response logging with Symfony Panther
<?php
use Symfony\Component\Panther\Client;
require 'vendor/autoload.php';
$client = Client::createFirefoxClient();
try {
$crawler = $client->request('GET', 'https://www.example.com/');
$client->executeScript(/** @lang JavaScript */ 'function addXMLRequestCallback(callback) {
var oldSend, i;
if(XMLHttpRequest.callbacks) {
XMLHttpRequest.callbacks.push(callback);
} else {
XMLHttpRequest.callbacks = [callback];
oldSend = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function() {
for(i = 0; i < XMLHttpRequest.callbacks.length; i++) {
XMLHttpRequest.callbacks[i](this);
}
oldSend.apply(this, arguments);
};
}
}
addXMLRequestCallback(function(xhr) {
//do nothing
});
window.ajax = [];
addXMLRequestCallback(function(xhr) {
window.ajax.push(xhr);
});');
//click some button on the page to trigger the ajax call
$crawler->filter('button')->click();
//wait a predetermined amount of time for the process to complete
sleep(1);
/** @noinspection JSUnresolvedVariable */
$xhrs = $client->executeScript(/** @lang JavaScript */ 'return window.ajax;');
foreach($xhrs as $xhr) {
echo "From {$xhr['responseURL']} came this response:\n{$xhr['response']}\n";
}
} catch(\Throwable $e) {
$filename = tempnam(sys_get_temp_dir(), 'screenshot_'); //will be png without the suffix
$client->takeScreenshot($filename);
echo "{$e->getMessage()} (Check $filename for screenshot)\n";
}
$client->quit();
$client->getBrowserManager()->quit();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment