Perform Puppeteer actions in Laravel controller using JavaScript code
P粉098417223
2023-08-28 09:40:29
<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>
I created a new js file for the JavaScript code
script.js
And in the controller I've made the changes:
This worked for me