diff --git a/README.md b/README.md index c2ce0220..2fffddcb 100644 --- a/README.md +++ b/README.md @@ -386,6 +386,16 @@ Browsershot also can get the body of an html page after JavaScript has been exec Browsershot::url('https://example.com')->bodyHtml(); // returns the html of the body ``` +### Evaluate + +Browsershot can get the evaluation of an html page: + +```php +Browsershot::url('https://example.com') + ->deviceScaleFactor(2) + ->evaluate("window.devicePixelRatio"); // returns 2 +``` + ### Misc #### Setting an arbitrary option diff --git a/bin/browser.js b/bin/browser.js index 6aadbed9..b970dfe0 100755 --- a/bin/browser.js +++ b/bin/browser.js @@ -2,6 +2,20 @@ const puppeteer = require('puppeteer'); const request = JSON.parse(process.argv[2]); +const getOutput = async (page, request) => { + let output; + + if (request.action == 'evaluate') { + output = await page.evaluate(request.options.pageFunction); + + return output; + } + + output = await page[request.action](request.options); + + return output.toString('base64'); +}; + const callChrome = async () => { let browser; let page; @@ -73,10 +87,10 @@ const callChrome = async () => { request.options.clip = await element.boundingBox(); } - output = await page[request.action](request.options); + output = await getOutput(page, request); if (!request.options.path) { - console.log(output.toString('base64')); + console.log(output); } await browser.close(); diff --git a/src/Browsershot.php b/src/Browsershot.php index 0822e01f..2c02f048 100644 --- a/src/Browsershot.php +++ b/src/Browsershot.php @@ -414,6 +414,13 @@ public function savePdf(string $targetPath) } } + public function evaluate(string $pageFunction): string + { + $command = $this->createEvaluateCommand($pageFunction); + + return $this->callBrowser($command); + } + public function applyManipulations(string $imagePath) { Image::load($imagePath) @@ -471,6 +478,17 @@ public function createPdfCommand($targetPath = null): array return $command; } + public function createEvaluateCommand(string $pageFunction): array + { + $url = $this->html ? $this->createTemporaryHtmlFile() : $this->url; + + $options = [ + 'pageFunction' => $pageFunction, + ]; + + return $this->createCommand($url, 'evaluate', $options); + } + protected function getOptionArgs(): array { $args = []; @@ -537,7 +555,7 @@ protected function callBrowser(array $command) $process->run(); if ($process->isSuccessful()) { - return $process->getOutput(); + return rtrim($process->getOutput()); } if ($process->getExitCode() === 2) { diff --git a/tests/BrowsershotTest.php b/tests/BrowsershotTest.php index 9522386e..fb8c4378 100644 --- a/tests/BrowsershotTest.php +++ b/tests/BrowsershotTest.php @@ -814,4 +814,13 @@ public function it_can_click_on_the_page() ], ], $command); } + + /** @test */ + public function it_can_evaluate_page() + { + $result = Browsershot::url('https://example.com') + ->evaluate('1 + 1'); + + $this->assertEquals('2', $result); + } }