diff --git a/bin/browser.cjs b/bin/browser.cjs index 7db609f6..9ce571ff 100644 --- a/bin/browser.cjs +++ b/bin/browser.cjs @@ -16,6 +16,8 @@ const request = args[0].startsWith('-f ') const requestsList = []; +const redirectHistory = []; + const consoleMessages = []; const failedRequests = []; @@ -29,6 +31,12 @@ const getOutput = async (page, request) => { return output; } + if (request.action == 'redirectHistory') { + output = JSON.stringify(redirectHistory); + + return output; + } + if (request.action == 'consoleMessages') { output = JSON.stringify(consoleMessages); @@ -118,6 +126,15 @@ const callChrome = async pup => { })); page.on('response', function (response) { + if (response.request().isNavigationRequest() && response.request().frame().parentFrame() === null) { + redirectHistory.push({ + url: response.request().url(), + status: response.status(), + reason: response.statusText(), + headers: response.headers() + }) + } + if (response.status() >= 200 && response.status() <= 399) { return; } diff --git a/src/Browsershot.php b/src/Browsershot.php index a67c7221..2a44e363 100644 --- a/src/Browsershot.php +++ b/src/Browsershot.php @@ -667,6 +667,13 @@ public function triggeredRequests(): array return json_decode($this->callBrowser($command), true); } + public function redirectHistory(): array + { + $command = $this->createRedirectHistoryCommand(); + + return json_decode($this->callBrowser($command), true); + } + /** * @return array{type: string, message: string, location:array} */ @@ -769,6 +776,15 @@ public function createTriggeredRequestsListCommand(): array return $this->createCommand($url, 'requestsList'); } + public function createRedirectHistoryCommand(): array + { + $url = $this->html + ? $this->createTemporaryHtmlFile() + : $this->url; + + return $this->createCommand($url, 'redirectHistory'); + } + public function createConsoleMessagesCommand(): array { $url = $this->html diff --git a/tests/BrowsershotTest.php b/tests/BrowsershotTest.php index 0706ebae..bb7cf45c 100644 --- a/tests/BrowsershotTest.php +++ b/tests/BrowsershotTest.php @@ -40,6 +40,33 @@ ); }); +it('can get the redirect history', function () { + $list = Browsershot::url('http://www.spatie.be') + ->redirectHistory(); + + $list = array_map(function($item) {unset($item['headers']); return $item;}, $list); + + expect($list)->toHaveCount(3); + + $this->assertEquals([ + [ + 'url' => 'http://www.spatie.be/', + 'status' => 301, + 'reason' => 'Moved Permanently' + ], + [ + 'url' => 'https://www.spatie.be/', + 'status' => 301, + 'reason' => '' + ], + [ + 'url' => 'https://spatie.be/', + 'status' => 200, + 'reason' => '' + ], + ], $list); +}); + it('will not allow a file url', function () { Browsershot::url('file://test'); })->throws(FileUrlNotAllowed::class);