-
-
Notifications
You must be signed in to change notification settings - Fork 108
Expand file tree
/
Copy pathContext.php
More file actions
121 lines (99 loc) · 2.84 KB
/
Context.php
File metadata and controls
121 lines (99 loc) · 2.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
<?php
declare(strict_types=1);
namespace Pest\Browser\Playwright;
use Exception;
/**
* @internal
*/
final class Context
{
use Concerns\InteractsWithPlaywright;
/**
* Indicates whether the browser context is closed.
*/
private bool $closed = false;
/**
* Creates a new context instance.
*/
public function __construct(
private readonly Browser $browser,
private readonly string $guid
) {
//
}
/**
* Gets the browser instance.
*/
public function browser(): Browser
{
return $this->browser;
}
/**
* Creates a new page in the context.
*/
public function newPage(): Page
{
$response = Client::instance()->execute($this->guid, 'newPage');
$frameGuid = '';
$pageGuid = '';
/** @var array{method: string|null, params: array{type: string|null, guid: string, initializer: array{url: string}}, result: array{page: array{guid: string|null}}} $message */
foreach ($response as $message) {
if (isset($message['method']) && $message['method'] === '__create__' && (isset($message['params']['type']) && $message['params']['type'] === 'Frame')) {
$frameGuid = $message['params']['guid'];
}
if (isset($message['result']['page']['guid'])) {
$pageGuid = $message['result']['page']['guid'];
}
}
return new Page($this, $pageGuid, $frameGuid);
}
/**
* Closes the browser context.
*/
public function close(): void
{
if ($this->browser->isClosed() || $this->closed) {
return;
}
try {
// fix this...
$response = $this->sendMessage('close');
$this->processVoidResponse($response);
} catch (Exception $e) {
if (str_contains($e->getMessage(), 'has been closed')) {
return;
}
throw $e;
}
$this->closed = true;
}
/**
* Checks if the browser context is closed.
*/
public function isClosed(): bool
{
return $this->closed;
}
/**
* Adds a script which will be evaluated.
*/
public function addInitScript(string $script): self
{
$response = $this->sendMessage('addInitScript', ['source' => $script]);
$this->processVoidResponse($response);
return $this;
}
/**
* Returns the current storage state (cookies and localStorage) as a JSON string.
*/
public function storageState(): string
{
$response = $this->sendMessage('storageState');
foreach ($response as $message) {
if (isset($message['result'])) {
return (string) json_encode($message['result']);
}
}
return '{"cookies":[],"origins":[]}';
}
}