Home  >  Q&A  >  body text

Perform Puppeteer actions in Laravel controller using JavaScript code

<p>I'm using Puppeteer to launch the browser from a laravel controller, but I don't know how to run JavaScript code from the controller</p> <p>My function is as follows:</p> <pre class="brush:php;toolbar:false;">$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();</pre> <p>When I try to run just this part of the code in node shell: </p> <pre class="brush:php;toolbar:false;">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(); })();</pre> <p>It works fine and I can see a browser opened. When I try to run the entire function it doesn't work. So I think the way I'm running the JS code in the controller is wrong. </p>
P粉098417223P粉098417223388 days ago474

reply all(1)I'll reply

  • P粉077701708

    P粉0777017082023-08-29 00:16:15

    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've made the changes:

    $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();

    This worked for me

    reply
    0
  • Cancelreply