Perform Puppeteer actions in Laravel controller using JavaScript code
P粉098417223
P粉098417223 2023-08-28 09:40:29
0
1
564
<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粉098417223
P粉098417223

reply all(1)
P粉077701708

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template