Skip to content

Commit c6e2817

Browse files
fsalehpourfreekmurze
authored andcommitted
Add method to make setting cookies easier (#212)
* Add method to make setting cookies easier * Remove extra blank line causing StyleCI check to fail
1 parent bb0aecb commit c6e2817

File tree

3 files changed

+41
-1
lines changed

3 files changed

+41
-1
lines changed

README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -508,6 +508,15 @@ Browsershot::url('https://example.com')
508508
...
509509
```
510510

511+
#### Setting Cookies
512+
513+
To add cookies to HTTP headers, pass an array containing cookie key/value pairs to `useCookies` method:
514+
515+
```php
516+
Browsershot::url('https://example.com')
517+
->useCookies(['Cookie-Key' => 'Cookie-Value'])
518+
...
519+
```
511520

512521
#### Clicking on the page
513522

src/Browsershot.php

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,13 @@ public function setChromePath(string $executablePath)
107107
return $this;
108108
}
109109

110+
public function useCookies(array $cookies)
111+
{
112+
$this->setExtraHttpHeaders(['Cookie' => http_build_query($cookies, null, '; ')]);
113+
114+
return $this;
115+
}
116+
110117
public function setExtraHttpHeaders(array $extraHTTPHeaders)
111118
{
112119
$this->setOption('extraHTTPHeaders', $extraHTTPHeaders);
@@ -586,7 +593,6 @@ protected function getFullCommand(array $command)
586593
.$nodeBinary.' '
587594
.escapeshellarg($binPath).' '
588595
.escapeshellarg(json_encode($command));
589-
590596
}
591597

592598
protected function getNodePathCommand(string $nodeBinary): string

tests/BrowsershotTest.php

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -778,6 +778,31 @@ public function it_can_send_extra_http_headers()
778778
], $command);
779779
}
780780

781+
/**
782+
* @test
783+
*/
784+
public function it_can_send_cookie_in_http_headers()
785+
{
786+
$command = Browsershot::url('https://example.com')
787+
->useCookies(['theme' => 'light', 'sessionToken' => 'abc123'])
788+
->createScreenshotCommand('screenshot.png');
789+
790+
$this->assertEquals([
791+
'url' => 'https://example.com',
792+
'action' => 'screenshot',
793+
'options' => [
794+
'extraHTTPHeaders' => ['Cookie' => 'theme=light; sessionToken=abc123'],
795+
'path' => 'screenshot.png',
796+
'viewport' => [
797+
'width' => 800,
798+
'height' => 600,
799+
],
800+
'args' => [],
801+
'type' => 'png',
802+
],
803+
], $command);
804+
}
805+
781806
/** @test */
782807
public function it_can_click_on_the_page()
783808
{

0 commit comments

Comments
 (0)