Executing Puppeteer scripts from a Laravel Controller

Hey everyone, I’m stuck trying to run Puppeteer from my Laravel controller. I’ve got this JavaScript code that works fine when I run it directly in Node, but I can’t figure out how to make it work from my Laravel app.

Here’s what I’m trying to do:

$puppeteerScript = <<<EOD
const webBot = require('webBot');
(async function() {
    const crawler = await webBot.init({visible: true});
    const webpage = await crawler.createTab();
    await webpage.navigate('https://example.com');
    const submitBtn = await webpage.findElement('button.submit');
    await submitBtn.trigger('click');
    await webpage.wait(5000);
    // More actions...
    await crawler.shutdown();
})();
EOD;

$executor = new ScriptRunner(['node', '-e', $puppeteerScript]);
$executor->execute();
$result = $executor->getResult();

When I run just the JavaScript part in Node, it opens a browser and does what I want. But when I try to run it from Laravel, nothing happens. I think I’m not calling the JavaScript correctly from PHP. Any ideas on what I’m doing wrong or how to fix this? Thanks!

hey tom, sounds like ur having trouble with the script execution. have u tried using symfony/process to run node commands? it’s pretty handy for this kinda stuff. something like:

use Symfony\Component\Process\Process;

$process = new Process(['node', '-e', $puppeteerScript]);
$process->run();

if (!$process->isSuccessful()) {
    throw new ProcessFailedException($process);
}

$result = $process->getOutput();

hope this helps! lmk if u need more info

I’ve encountered similar challenges when invoking Puppeteer from Laravel. One solution that worked well for me involved leveraging Laravel’s built-in Job system. I created a dedicated job to manage the Puppeteer script execution, using PHP functions like shell_exec or exec to trigger Node.js. Dispatching the job from the controller helped to better manage potential timeouts and allowed the task to run asynchronously if needed. Make sure that Node.js and its necessary packages are installed and check your server’s security settings as some hosts restrict external script executions.