Search code examples
javascriptphplaravelcontrollerpuppeteer

Use JavaScript Code to run Puppeteer from Laravel Controller


I am using Puppeteer to launch a browser from a laravel controller, however i don't know how to run the JavaScript code from the controller

My function looks like this:

$script = <<<SCRIPT
    const puppeteer = require('puppeteer');
    (async () => {
        const browser = await puppeteer.launch({headless: false});
        const page = await browser.newPage();
        await page.goto('http://my-url.com');
        const button = await page.$('button#button');
        await button.evaluate( button => button.click() );
        await page.waitForTimeout(5000);
        ...
        await browser.close();
    })();
    SCRIPT;
$process = new Process(['node', '-e', $script]);
$process->run();
$output = $process->getOutput();

When i try to run just this part of the code in the node shell:

const puppeteer = require('puppeteer');
(async () => {
    const browser = await puppeteer.launch({headless: false});     
    const page = await browser.newPage();
    await page.goto('http://my-url.com');
    const button = await page.$('button#button');
    await button.evaluate( button => button.click() );
    await page.waitForTimeout(5000);
    ...
    await browser.close();
})();

it works fine and I can also see a browser being opened. When I try to run the whole function it doesn't work. SO I presume that the way i'm running the JS code in the controller is wrong.


Solution

  • I created a new js File for the JavaScript Code script.js

    // script.js
    
    const puppeteer = require('puppeteer');
    (async () => {
        const browser = await puppeteer.launch({headless: false});     
        const page = await browser.newPage();
        await page.goto('http://my-url.com');
        const button = await page.$('button#button');
        await button.evaluate( button => button.click() );
        await page.waitForTimeout(5000);
        ...
        await browser.close();
    })();
    

    And in the controller i have changed:

    $process = new Process(['path/to/node', 'path/to/script.js]);
    $process->run();
    if(!$process->isSuccessful()) {
      throw new ProcessFailedException($process);
    }
    $output = $process->getOutput();
    $errors = $process->getErrorOutput();
    

    That worked for me