forked from Kaliiiiiiiiii-Vinyzu/patchright
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpatchright.patch
More file actions
9212 lines (8843 loc) · 399 KB
/
patchright.patch
File metadata and controls
9212 lines (8843 loc) · 399 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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# NOTE: This patch file is generated automatically and is not used, it is only for documentation. The driver is actually patched using [patchright_driver_patch](https://github.com/Kaliiiiiiiiii-Vinyzu/patchright/blob/main/patchright_driver_patch.ts), see [the workflow](https://github.com/Kaliiiiiiiiii-Vinyzu/patchright/blob/main/.github/workflows/patch_file_updater.yml)
diff -ruN -x protocol.yml --minimal playwright/node_modules/playwright-core/src/cli/program.ts patchright/node_modules/playwright-core/src/cli/program.ts
---
+++
@@ -1,21 +1,3 @@
-/**
- * Copyright (c) Microsoft Corporation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* eslint-disable no-console */
-
import '../bootstrap';
import { gracefullyProcessExitDoNotHang, getPackageManagerExecCommand } from '../utils';
import { addTraceCommands } from '../tools/trace/traceCli';
@@ -69,10 +51,10 @@
program
.command('install [browser...]')
- .description('ensure browsers necessary for this version of Playwright are installed')
+ .description('ensure browsers necessary for this version of Patchright are installed')
.option('--with-deps', 'install system dependencies for browsers')
.option('--dry-run', 'do not execute installation, only print information')
- .option('--list', 'prints list of browsers from all playwright installations')
+ .option('--list', 'prints list of browsers from all patchright installations')
.option('--force', 'force reinstall of already installed browsers')
.option('--only-shell', 'only install headless shell when installing chromium')
.option('--no-shell', 'do not install chromium headless shell')
@@ -95,8 +77,8 @@
program
.command('uninstall')
- .description('Removes browsers used by this installation of Playwright from the system (chromium, firefox, webkit, ffmpeg). This does not include branded channels.')
- .option('--all', 'Removes all browsers used by any Playwright installation from the system.')
+ .description('Removes browsers used by this installation of Patchright from the system (chromium, firefox, webkit, ffmpeg). This does not include branded channels.')
+ .option('--all', 'Removes all browsers used by any Patchright installation from the system.')
.action(async (options: { all?: boolean }) => {
const { uninstallBrowsers } = await import('./installActions');
uninstallBrowsers(options).catch(logErrorAndExit);
@@ -284,7 +266,7 @@
.option('--save-har-glob <glob pattern>', 'filter entries in the HAR by matching url against this glob pattern')
.option('--save-storage <filename>', 'save context storage state at the end, for later use with --load-storage')
.option('--timezone <time zone>', 'time zone to emulate, for example "Europe/Rome"')
- .option('--timeout <timeout>', 'timeout for Playwright actions in milliseconds, no timeout by default')
+ .option('--timeout <timeout>', 'timeout for Patchright actions in milliseconds, no timeout by default')
.option('--user-agent <ua string>', 'specify user agent string')
.option('--user-data-dir <directory>', 'use the specified user data directory instead of a new context')
.option('--viewport-size <size>', 'specify browser viewport size in pixels, for example "1280, 720"');
@@ -293,14 +275,14 @@
function buildBasePlaywrightCLICommand(cliTargetLang: string | undefined): string {
switch (cliTargetLang) {
case 'python':
- return `playwright`;
+ return `patchright`;
case 'java':
return `mvn exec:java -e -D exec.mainClass=com.microsoft.playwright.CLI -D exec.args="...options.."`;
case 'csharp':
return `pwsh bin/Debug/netX/playwright.ps1`;
default: {
const packageManagerCommand = getPackageManagerExecCommand();
- return `${packageManagerCommand} playwright`;
+ return `${packageManagerCommand} patchright`;
}
}
}
diff -ruN -x protocol.yml --minimal playwright/node_modules/playwright-core/src/cli/programWithTestStub.ts patchright/node_modules/playwright-core/src/cli/programWithTestStub.ts
---
+++
@@ -1,21 +1,3 @@
-/**
- * Copyright (c) Microsoft Corporation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/* eslint-disable no-console */
-
import { gracefullyProcessExitDoNotHang } from '../server/utils/processLauncher';
import { getPackageManager } from '../utils';
import { program } from './program';
@@ -34,24 +16,24 @@
packages.push('playwright');
const packageManager = getPackageManager();
if (packageManager === 'yarn') {
- console.error(`Please install @playwright/test package before running "yarn playwright ${command}"`);
+ console.error(`Please install @playwright/test package before running "yarn patchright ${command}"`);
console.error(` yarn remove ${packages.join(' ')}`);
console.error(' yarn add -D @playwright/test');
} else if (packageManager === 'pnpm') {
- console.error(`Please install @playwright/test package before running "pnpm exec playwright ${command}"`);
+ console.error(`Please install @playwright/test package before running "pnpm exec patchright ${command}"`);
console.error(` pnpm remove ${packages.join(' ')}`);
console.error(' pnpm add -D @playwright/test');
} else {
- console.error(`Please install @playwright/test package before running "npx playwright ${command}"`);
+ console.error(`Please install @playwright/test package before running "npx patchright ${command}"`);
console.error(` npm uninstall ${packages.join(' ')}`);
console.error(' npm install -D @playwright/test');
}
}
const kExternalPlaywrightTestCommands = [
- ['test', 'Run tests with Playwright Test.'],
- ['show-report', 'Show Playwright Test HTML report.'],
- ['merge-reports', 'Merge Playwright Test Blob reports'],
+ ['test', 'Run tests with Patchright Test.'],
+ ['show-report', 'Show Patchright Test HTML report.'],
+ ['merge-reports', 'Merge Patchright Test Blob reports'],
];
function addExternalPlaywrightTestCommands() {
for (const [command, description] of kExternalPlaywrightTestCommands) {
diff -ruN -x protocol.yml --minimal playwright/node_modules/playwright-core/src/client/browserContext.ts patchright/node_modules/playwright-core/src/client/browserContext.ts
---
+++
@@ -146,9 +146,9 @@
// a) removing "dialog" listener subscription (client->server)
// b) actual "dialog" event (server->client)
if (dialogObject.type() === 'beforeunload')
- dialog.accept({}).catch(() => {});
+ dialogObject._wrapApiCall(() => dialog.accept({}).catch(() => {}), { internal: true });
else
- dialog.dismiss().catch(() => {});
+ dialogObject._wrapApiCall(() => dialog.dismiss().catch(() => {}), { internal: true });
}
});
this._channel.on('request', ({ request, page }) => this._onRequest(network.Request.from(request), Page.fromNullable(page)));
@@ -356,17 +356,20 @@
}
async addInitScript(script: Function | string | { path?: string, content?: string }, arg?: any) {
+ await this.installInjectRoute();
const source = await evaluationScript(this._platform, script, arg);
return DisposableObject.from((await this._channel.addInitScript({ source })).disposable);
}
async exposeBinding(name: string, callback: (source: structs.BindingSource, ...args: any[]) => any, options: { handle?: boolean } = {}): Promise<DisposableObject> {
+ await this.installInjectRoute();
const result = await this._channel.exposeBinding({ name, needsHandle: options.handle });
this._bindings.set(name, callback);
return DisposableObject.from(result.disposable);
}
async exposeFunction(name: string, callback: Function): Promise<DisposableObject> {
+ await this.installInjectRoute();
const result = await this._channel.exposeBinding({ name });
const binding = (source: structs.BindingSource, ...args: any[]) => callback(...args);
this._bindings.set(name, binding);
@@ -560,6 +563,25 @@
await this._channel.exposeConsoleApi();
}
+ routeInjecting: boolean = false;
+
+ async installInjectRoute() {
+
+ if (this.routeInjecting) return;
+ await this.route('**/*', async route => {
+ try {
+ if (route.request().resourceType() === 'document' && route.request().url().startsWith('http')) {
+ const protocol = route.request().url().split(':')[0];
+ await route.fallback({ url: protocol + '://patchright-init-script-inject.internal/' });
+ } else {
+ await route.fallback();
+ }
+ } catch (error) {
+ await route.fallback();
+ }
+ });
+ this.routeInjecting = true;
+ }
}
async function prepareStorageState(platform: Platform, storageState: string | SetStorageState): Promise<NonNullable<channels.BrowserNewContextParams['storageState']>> {
diff -ruN -x protocol.yml --minimal playwright/node_modules/playwright-core/src/client/clientHelper.ts patchright/node_modules/playwright-core/src/client/clientHelper.ts
---
+++
@@ -50,5 +50,5 @@
}
export function addSourceUrlToScript(source: string, path: string): string {
- return `${source}\n//# sourceURL=${path.replace(/\n/g, '')}`;
+ return source
}
diff -ruN -x protocol.yml --minimal playwright/node_modules/playwright-core/src/client/clock.ts patchright/node_modules/playwright-core/src/client/clock.ts
---
+++
@@ -25,6 +25,7 @@
}
async install(options: { time?: number | string | Date } = { }) {
+ await this._browserContext.installInjectRoute()
await this._browserContext._channel.clockInstall(options.time !== undefined ? parseTime(options.time) : {});
}
diff -ruN -x protocol.yml --minimal playwright/node_modules/playwright-core/src/client/frame.ts patchright/node_modules/playwright-core/src/client/frame.ts
---
+++
@@ -177,25 +177,33 @@
}
async waitForURL(url: URLMatch, options: { waitUntil?: LifecycleEvent, timeout?: number } = {}): Promise<void> {
- if (urlMatches(this._page?.context()._options.baseURL, this.url(), url))
- return await this.waitForLoadState(options.waitUntil, options);
- await this.waitForNavigation({ url, ...options });
+ if (urlMatches(this._page?.context()._options.baseURL, this.url(), url))
+ return await this.waitForLoadState(options.waitUntil, options);
+ try {
+ await this.waitForNavigation({ url, ...options });
+ } catch (error) {
+ if (urlMatches(this._page?.context()._options.baseURL, this.url(), url)) {
+ await this.waitForLoadState(options.waitUntil, options);
+ return;
+ }
+ throw error;
+ }
}
async frameElement(): Promise<ElementHandle> {
return ElementHandle.from((await this._channel.frameElement()).element);
}
- async evaluateHandle<R, Arg>(pageFunction: structs.PageFunction<Arg, R>, arg?: Arg): Promise<structs.SmartHandle<R>> {
- assertMaxArguments(arguments.length, 2);
- const result = await this._channel.evaluateExpressionHandle({ expression: String(pageFunction), isFunction: typeof pageFunction === 'function', arg: serializeArgument(arg) });
+ async evaluateHandle<R, Arg>(pageFunction: structs.PageFunction<Arg, R>, arg?: Arg, isolatedContext: boolean = true): Promise<structs.SmartHandle<R>> {
+ assertMaxArguments(arguments.length, 3);
+ const result = await this._channel.evaluateExpressionHandle({ expression: String(pageFunction), isFunction: typeof pageFunction === 'function', arg: serializeArgument(arg), isolatedContext: isolatedContext });
return JSHandle.from(result.handle) as any as structs.SmartHandle<R>;
}
- async evaluate<R, Arg>(pageFunction: structs.PageFunction<Arg, R>, arg?: Arg): Promise<R> {
- assertMaxArguments(arguments.length, 2);
- const result = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === 'function', arg: serializeArgument(arg) });
+ async evaluate<R, Arg>(pageFunction: structs.PageFunction<Arg, R>, arg?: Arg, isolatedContext: boolean = true): Promise<R> {
+ assertMaxArguments(arguments.length, 3);
+ const result = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === 'function', arg: serializeArgument(arg), isolatedContext: isolatedContext });
return parseResult(result.value);
}
@@ -231,9 +239,9 @@
return parseResult(result.value);
}
- async $$eval<R, Arg>(selector: string, pageFunction: structs.PageFunctionOn<Element[], Arg, R>, arg?: Arg): Promise<R> {
- assertMaxArguments(arguments.length, 3);
- const result = await this._channel.evalOnSelectorAll({ selector, expression: String(pageFunction), isFunction: typeof pageFunction === 'function', arg: serializeArgument(arg) });
+ async $$eval<R, Arg>(selector: string, pageFunction: structs.PageFunctionOn<Element[], Arg, R>, arg?: Arg, isolatedContext: boolean = true): Promise<R> {
+ assertMaxArguments(arguments.length, 4);
+ const result = await this._channel.evalOnSelectorAll({ selector, expression: String(pageFunction), isFunction: typeof pageFunction === 'function', arg: serializeArgument(arg), isolatedContext: isolatedContext });
return parseResult(result.value);
}
diff -ruN -x protocol.yml --minimal playwright/node_modules/playwright-core/src/client/jsHandle.ts patchright/node_modules/playwright-core/src/client/jsHandle.ts
---
+++
@@ -36,14 +36,16 @@
this._channel.on('previewUpdated', ({ preview }) => this._preview = preview);
}
- async evaluate<R, Arg>(pageFunction: structs.PageFunctionOn<T, Arg, R>, arg?: Arg): Promise<R> {
- const result = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === 'function', arg: serializeArgument(arg) });
- return parseResult(result.value);
+ async evaluate<R, Arg>(pageFunction: structs.PageFunctionOn<T, Arg, R>, arg?: Arg, isolatedContext: boolean = true): Promise<R> {
+
+ const result = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === 'function', arg: serializeArgument(arg), isolatedContext: isolatedContext });
+ return parseResult(result.value);
}
- async evaluateHandle<R, Arg>(pageFunction: structs.PageFunctionOn<T, Arg, R>, arg?: Arg): Promise<structs.SmartHandle<R>> {
- const result = await this._channel.evaluateExpressionHandle({ expression: String(pageFunction), isFunction: typeof pageFunction === 'function', arg: serializeArgument(arg) });
- return JSHandle.from(result.handle) as any as structs.SmartHandle<R>;
+ async evaluateHandle<R, Arg>(pageFunction: structs.PageFunctionOn<T, Arg, R>, arg?: Arg, isolatedContext: boolean = true): Promise<structs.SmartHandle<R>> {
+
+ const result = await this._channel.evaluateExpressionHandle({ expression: String(pageFunction), isFunction: typeof pageFunction === 'function', arg: serializeArgument(arg), isolatedContext: isolatedContext });
+ return JSHandle.from(result.handle) as any as structs.SmartHandle<R>;
}
async getProperty(propertyName: string): Promise<JSHandle> {
diff -ruN -x protocol.yml --minimal playwright/node_modules/playwright-core/src/client/locator.ts patchright/node_modules/playwright-core/src/client/locator.ts
---
+++
@@ -1,3 +1,5 @@
+// undetected-undetected_playwright-patch - custom imports
+import { JSHandle, parseResult, serializeArgument } from './jsHandle';
/**
* Copyright (c) Microsoft Corporation.
*
@@ -124,16 +126,52 @@
});
}
- async evaluate<R, Arg>(pageFunction: structs.PageFunctionOn<SVGElement | HTMLElement, Arg, R>, arg?: Arg, options?: TimeoutOptions): Promise<R> {
- return await this._withElement(h => h.evaluate(pageFunction, arg), { title: 'Evaluate', timeout: options?.timeout });
+ async evaluate<R, Arg>(pageFunction: structs.PageFunctionOn<SVGElement | HTMLElement, Arg, R>, arg?: Arg, options?: TimeoutOptions, isolatedContext: boolean = true): Promise<R> {
+
+ if (typeof options === 'boolean') {
+ isolatedContext = options;
+ options = undefined;
+ }
+ return await this._withElement(
+ async (h) =>
+ parseResult(
+ (
+ await h._channel.evaluateExpression({
+ expression: String(pageFunction),
+ isFunction: typeof pageFunction === "function",
+ arg: serializeArgument(arg),
+ isolatedContext: isolatedContext,
+ })
+ ).value
+ ),
+ { title: "Evaluate", timeout: options?.timeout }
+ );
}
- async evaluateAll<R, Arg>(pageFunction: structs.PageFunctionOn<Element[], Arg, R>, arg?: Arg): Promise<R> {
- return await this._frame.$$eval(this._selector, pageFunction, arg);
+ async evaluateAll<R, Arg>(pageFunction: structs.PageFunctionOn<Element[], Arg, R>, arg?: Arg, isolatedContext: boolean = true): Promise<R> {
+ return await this._frame.$$eval(this._selector, pageFunction, arg, isolatedContext);
}
- async evaluateHandle<R, Arg>(pageFunction: structs.PageFunctionOn<any, Arg, R>, arg?: Arg, options?: TimeoutOptions): Promise<structs.SmartHandle<R>> {
- return await this._withElement(h => h.evaluateHandle(pageFunction, arg), { title: 'Evaluate', timeout: options?.timeout });
+ async evaluateHandle<R, Arg>(pageFunction: structs.PageFunctionOn<any, Arg, R>, arg?: Arg, options?: TimeoutOptions, isolatedContext: boolean = true): Promise<structs.SmartHandle<R>> {
+
+ if (typeof options === 'boolean') {
+ isolatedContext = options;
+ options = undefined;
+ }
+ return await this._withElement(
+ async (h) =>
+ JSHandle.from(
+ (
+ await h._channel.evaluateExpressionHandle({
+ expression: String(pageFunction),
+ isFunction: typeof pageFunction === "function",
+ arg: serializeArgument(arg),
+ isolatedContext: isolatedContext,
+ })
+ ).handle
+ ) as any as structs.SmartHandle<R>,
+ { title: "Evaluate", timeout: options?.timeout }
+ );
}
async fill(value: string, options: channels.ElementHandleFillOptions & TimeoutOptions = {}): Promise<void> {
diff -ruN -x protocol.yml --minimal playwright/node_modules/playwright-core/src/client/network.ts patchright/node_modules/playwright-core/src/client/network.ts
---
+++
@@ -15,7 +15,7 @@
*/
import { ChannelOwner } from './channelOwner';
-import { isTargetClosedError } from './errors';
+import { isTargetClosedError, TargetClosedError } from './errors';
import { Events } from './events';
import { APIResponse } from './fetch';
import { Frame } from './frame';
@@ -183,7 +183,12 @@
}
async allHeaders(): Promise<Headers> {
- return (await this._actualHeaders()).headers();
+
+ const headers = await this._actualHeaders();
+ const page = this._safePage();
+ if (page?._closeWasCalled)
+ throw new TargetClosedError();
+ return headers.headers();
}
async headersArray(): Promise<HeadersArray> {
diff -ruN -x protocol.yml --minimal playwright/node_modules/playwright-core/src/client/page.ts patchright/node_modules/playwright-core/src/client/page.ts
---
+++
@@ -313,9 +313,9 @@
return await this._mainFrame.dispatchEvent(selector, type, eventInit, options);
}
- async evaluateHandle<R, Arg>(pageFunction: structs.PageFunction<Arg, R>, arg?: Arg): Promise<structs.SmartHandle<R>> {
- assertMaxArguments(arguments.length, 2);
- return await this._mainFrame.evaluateHandle(pageFunction, arg);
+ async evaluateHandle<R, Arg>(pageFunction: structs.PageFunction<Arg, R>, arg?: Arg, isolatedContext: boolean = true): Promise<structs.SmartHandle<R>> {
+ assertMaxArguments(arguments.length, 3);
+ return await this._mainFrame.evaluateHandle(pageFunction, arg, isolatedContext);
}
async $eval<R, Arg>(selector: string, pageFunction: structs.PageFunctionOn<Element, Arg, R>, arg?: Arg): Promise<R> {
@@ -341,6 +341,7 @@
}
async exposeFunction(name: string, callback: Function) {
+ await this.installInjectRoute();
const result = await this._channel.exposeBinding({ name });
const binding = (source: structs.BindingSource, ...args: any[]) => callback(...args);
this._bindings.set(name, binding);
@@ -348,6 +349,7 @@
}
async exposeBinding(name: string, callback: (source: structs.BindingSource, ...args: any[]) => any, options: { handle?: boolean } = {}) {
+ await this.installInjectRoute();
const result = await this._channel.exposeBinding({ name, needsHandle: options.handle });
this._bindings.set(name, callback);
return DisposableObject.from(result.disposable);
@@ -507,12 +509,13 @@
return this._viewportSize || null;
}
- async evaluate<R, Arg>(pageFunction: structs.PageFunction<Arg, R>, arg?: Arg): Promise<R> {
- assertMaxArguments(arguments.length, 2);
- return await this._mainFrame.evaluate(pageFunction, arg);
+ async evaluate<R, Arg>(pageFunction: structs.PageFunction<Arg, R>, arg?: Arg, isolatedContext: boolean = true): Promise<R> {
+ assertMaxArguments(arguments.length, 3);
+ return await this._mainFrame.evaluate(pageFunction, arg, isolatedContext);
}
async addInitScript(script: Function | string | { path?: string, content?: string }, arg?: any) {
+ await this.installInjectRoute();
const source = await evaluationScript(this._platform, script, arg);
return DisposableObject.from((await this._channel.addInitScript({ source })).disposable);
}
@@ -864,6 +867,26 @@
async _setDockTile(image: Buffer) {
await this._channel.setDockTile({ image });
}
+
+ routeInjecting: boolean = false;
+
+ async installInjectRoute() {
+
+ if (this.routeInjecting || this.context().routeInjecting) return;
+ await this.route('**/*', async route => {
+ try {
+ if (route.request().resourceType() === 'document' && route.request().url().startsWith('http')) {
+ const protocol = route.request().url().split(':')[0];
+ await route.fallback({ url: protocol + '://patchright-init-script-inject.internal/' });
+ } else {
+ await route.fallback();
+ }
+ } catch (error) {
+ await route.fallback();
+ }
+ });
+ this.routeInjecting = true;
+ }
}
export class BindingCall extends ChannelOwner<channels.BindingCallChannel> {
diff -ruN -x protocol.yml --minimal playwright/node_modules/playwright-core/src/client/tracing.ts patchright/node_modules/playwright-core/src/client/tracing.ts
---
+++
@@ -38,6 +38,7 @@
}
async start(options: { name?: string, title?: string, snapshots?: boolean, screenshots?: boolean, sources?: boolean, live?: boolean } = {}) {
+ if (typeof this._parent.installInjectRoute === 'function') await this._parent.installInjectRoute();
await this._wrapApiCall(async () => {
this._includeSources = !!options.sources;
this._isLive = !!options.live;
diff -ruN -x protocol.yml --minimal playwright/node_modules/playwright-core/src/client/worker.ts patchright/node_modules/playwright-core/src/client/worker.ts
---
+++
@@ -62,15 +62,15 @@
return this._initializer.url;
}
- async evaluate<R, Arg>(pageFunction: structs.PageFunction<Arg, R>, arg?: Arg): Promise<R> {
- assertMaxArguments(arguments.length, 2);
- const result = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === 'function', arg: serializeArgument(arg) });
+ async evaluate<R, Arg>(pageFunction: structs.PageFunction<Arg, R>, arg?: Arg, isolatedContext: boolean = true): Promise<R> {
+ assertMaxArguments(arguments.length, 3);
+ const result = await this._channel.evaluateExpression({ expression: String(pageFunction), isFunction: typeof pageFunction === 'function', arg: serializeArgument(arg), isolatedContext: isolatedContext });
return parseResult(result.value);
}
- async evaluateHandle<R, Arg>(pageFunction: structs.PageFunction<Arg, R>, arg?: Arg): Promise<structs.SmartHandle<R>> {
- assertMaxArguments(arguments.length, 2);
- const result = await this._channel.evaluateExpressionHandle({ expression: String(pageFunction), isFunction: typeof pageFunction === 'function', arg: serializeArgument(arg) });
+ async evaluateHandle<R, Arg>(pageFunction: structs.PageFunction<Arg, R>, arg?: Arg, isolatedContext: boolean = true): Promise<structs.SmartHandle<R>> {
+ assertMaxArguments(arguments.length, 3);
+ const result = await this._channel.evaluateExpressionHandle({ expression: String(pageFunction), isFunction: typeof pageFunction === 'function', arg: serializeArgument(arg), isolatedContext: isolatedContext });
return JSHandle.from(result.handle) as any as structs.SmartHandle<R>;
}
diff -ruN -x protocol.yml --minimal playwright/node_modules/playwright-core/src/server/android/android.ts patchright/node_modules/playwright-core/src/server/android/android.ts
---
+++
@@ -1,19 +1,3 @@
-/**
- * Copyright Microsoft Corporation. All rights reserved.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
import { EventEmitter } from 'events';
import fs from 'fs';
import os from 'os';
@@ -184,7 +168,7 @@
for (const file of ['android-driver.apk', 'android-driver-target.apk']) {
const fullName = path.join(executable.directory!, file);
if (!fs.existsSync(fullName))
- throw new Error(`Please install Android driver apk using '${packageManagerCommand} playwright install android'`);
+ throw new Error(`Please install Android driver apk using '${packageManagerCommand} patchright install android'`);
await this.installApk(progress, await progress.race(fs.promises.readFile(fullName)));
}
} else {
diff -ruN -x protocol.yml --minimal playwright/node_modules/playwright-core/src/server/browserContext.ts patchright/node_modules/playwright-core/src/server/browserContext.ts
---
+++
@@ -167,7 +167,7 @@
await this.exposeConsoleApi();
if (this._options.serviceWorkers === 'block')
- await this.addInitScript(`\nif (navigator.serviceWorker) navigator.serviceWorker.register = async () => { console.warn('Service Worker registration blocked by Playwright'); };\n`);
+ await this.addInitScript(`if (navigator.serviceWorker) navigator.serviceWorker.register = async () => { };`);
if (this._options.permissions)
await this.grantPermissions(this._options.permissions);
@@ -352,18 +352,13 @@
if (page.getBinding(name))
throw new Error(`Function "${name}" has been already registered in one of the pages`);
}
- await progress.race(this.exposePlaywrightBindingIfNeeded());
const binding = new PageBinding(this, name, playwrightBinding, needsHandle);
binding.forClient = forClient;
this._pageBindings.set(name, binding);
- try {
- await progress.race(this.doAddInitScript(binding.initScript));
- await progress.race(this.safeNonStallingEvaluateInAllFrames(binding.initScript.source, 'main'));
- return binding;
- } catch (error) {
- this._pageBindings.delete(name);
- throw error;
- }
+
+ await this.doExposeBinding(binding);
+ return binding;
+
}
async removeExposedBinding(binding: PageBinding) {
@@ -881,4 +876,5 @@
strictSelectors: false,
serviceWorkers: 'allow',
locale: 'en-US',
+ focusControl: false
};
diff -ruN -x protocol.yml --minimal playwright/node_modules/playwright-core/src/server/chromium/chromium.ts patchright/node_modules/playwright-core/src/server/chromium/chromium.ts
---
+++
@@ -320,8 +320,6 @@
const chromeArguments = [...chromiumSwitches(options.assistantMode, options.channel)];
// See https://issues.chromium.org/issues/40277080
- chromeArguments.push('--enable-unsafe-swiftshader');
-
if (options.headless) {
chromeArguments.push('--headless');
diff -ruN -x protocol.yml --minimal playwright/node_modules/playwright-core/src/server/chromium/chromiumSwitches.ts patchright/node_modules/playwright-core/src/server/chromium/chromiumSwitches.ts
---
+++
@@ -51,26 +51,16 @@
'--disable-field-trial-config', // https://source.chromium.org/chromium/chromium/src/+/main:testing/variations/README.md
'--disable-background-networking',
'--disable-background-timer-throttling',
- '--disable-backgrounding-occluded-windows',
- '--disable-back-forward-cache', // Avoids surprises like main request not being intercepted during page.goBack().
- '--disable-breakpad',
- '--disable-client-side-phishing-detection',
- '--disable-component-extensions-with-background-pages',
- '--disable-component-update', // Avoids unneeded network activity after startup.
+ '--disable-backgrounding-occluded-windows', // Avoids surprises like main request not being intercepted during page.goBack().
+ '--disable-breakpad', // Avoids unneeded network activity after startup.
'--no-default-browser-check',
- '--disable-default-apps',
'--disable-dev-shm-usage',
- '--disable-extensions',
'--disable-features=' + disabledFeatures(assistantMode).join(','),
process.env.PLAYWRIGHT_LEGACY_SCREENSHOT ? '' : '--enable-features=CDPScreenshotNewSurface',
- '--allow-pre-commit-input',
'--disable-hang-monitor',
- '--disable-ipc-flooding-protection',
- '--disable-popup-blocking',
'--disable-prompt-on-repost',
'--disable-renderer-backgrounding',
'--force-color-profile=srgb',
- '--metrics-recording-only',
'--no-first-run',
'--password-store=basic',
'--use-mock-keychain',
@@ -79,11 +69,8 @@
'--export-tagged-pdf',
// https://chromium-review.googlesource.com/c/chromium/src/+/4853540
'--disable-search-engine-choice-screen',
- // https://issues.chromium.org/41491762
- '--unsafely-disable-devtools-self-xss-warnings',
// Edge can potentially restart on Windows (msRelaunchNoCompatLayer) which looses its file descriptors (stdout/stderr) and CDP (3/4). Disable until fixed upstream.
'--edge-skip-compat-layer-relaunch',
- assistantMode ? '' : '--enable-automation',
// This disables Chrome for Testing infobar that is visible in the persistent context.
// The switch is ignored everywhere else, including Chromium/Chrome/Edge.
'--disable-infobars',
@@ -91,4 +78,5 @@
'--disable-search-engine-choice-screen',
// Prevents the "three dots" menu crash in IdentityManager::HasPrimaryAccount for ephemeral contexts.
android ? '' : '--disable-sync',
+ '--disable-blink-features=AutomationControlled'
].filter(Boolean);
diff -ruN -x protocol.yml --minimal playwright/node_modules/playwright-core/src/server/chromium/crBrowser.ts patchright/node_modules/playwright-core/src/server/chromium/crBrowser.ts
---
+++
@@ -522,8 +522,10 @@
}
async doRemoveInitScripts(initScripts: InitScript[]) {
- for (const page of this.pages())
- await (page.delegate as CRPage).removeInitScripts(initScripts);
+
+ for (const page of this.pages())
+ await (page.delegate as CRPage).removeInitScripts(initScripts);
+
}
async doUpdateRequestInterception(): Promise<void> {
@@ -611,6 +613,20 @@
const rootSession = await this._browser._clientRootSession();
return rootSession.attachToTarget(targetId);
}
+
+ async doExposeBinding(binding: PageBinding) {
+
+ for (const page of this.pages())
+ await (page.delegate as CRPage).exposeBinding(binding);
+
+ }
+
+ async doRemoveExposedBindings() {
+
+ for (const page of this.pages())
+ await (page.delegate as CRPage).removeExposedBindings();
+
+ }
}
export function shouldProxyLoopback(bypass: string | undefined) {
diff -ruN -x protocol.yml --minimal playwright/node_modules/playwright-core/src/server/chromium/crCoverage.ts patchright/node_modules/playwright-core/src/server/chromium/crCoverage.ts
---
+++
@@ -82,10 +82,13 @@
this._scriptIds.clear();
this._scriptSources.clear();
this._eventListeners = [
- eventsHelper.addEventListener(this._client, 'Debugger.scriptParsed', this._onScriptParsed.bind(this)),
- eventsHelper.addEventListener(this._client, 'Runtime.executionContextsCleared', this._onExecutionContextsCleared.bind(this)),
- eventsHelper.addEventListener(this._client, 'Debugger.paused', this._onDebuggerPaused.bind(this)),
- ];
+ eventsHelper.addEventListener(this._client, 'Debugger.scriptParsed', this._onScriptParsed.bind(this)),
+
+ eventsHelper.addEventListener(this._client, 'Runtime.executionContextsCleared', this._onExecutionContextsCleared.bind(this)),
+ eventsHelper.addEventListener(this._client, 'Page.frameNavigated', this._onFrameNavigated.bind(this)),
+
+ eventsHelper.addEventListener(this._client, 'Debugger.paused', this._onDebuggerPaused.bind(this)),
+ ];
await Promise.all([
this._client.send('Profiler.enable'),
this._client.send('Profiler.startPreciseCoverage', { callCount: true, detailed: true }),
@@ -142,6 +145,11 @@
}
return coverage;
}
+
+ _onFrameNavigated(event: Protocol.Page.frameNavigatedPayload) {
+ if (event.frame.parentId) return;
+ this._onExecutionContextsCleared();
+ }
}
class CSSCoverage {
@@ -169,9 +177,12 @@
this._stylesheetURLs.clear();
this._stylesheetSources.clear();
this._eventListeners = [
- eventsHelper.addEventListener(this._client, 'CSS.styleSheetAdded', this._onStyleSheet.bind(this)),
- eventsHelper.addEventListener(this._client, 'Runtime.executionContextsCleared', this._onExecutionContextsCleared.bind(this)),
- ];
+ eventsHelper.addEventListener(this._client, 'CSS.styleSheetAdded', this._onStyleSheet.bind(this)),
+
+ eventsHelper.addEventListener(this._client, 'Runtime.executionContextsCleared', this._onExecutionContextsCleared.bind(this)),
+ eventsHelper.addEventListener(this._client, 'Page.frameNavigated', this._onFrameNavigated.bind(this)),
+
+ ];
await Promise.all([
this._client.send('DOM.enable'),
this._client.send('CSS.enable'),
@@ -235,6 +246,11 @@
return coverage;
}
+
+ _onFrameNavigated(event: Protocol.Page.frameNavigatedPayload) {
+ if (event.frame.parentId) return;
+ this._onExecutionContextsCleared();
+ }
}
function convertToDisjointRanges(nestedRanges: {
diff -ruN -x protocol.yml --minimal playwright/node_modules/playwright-core/src/server/chromium/crDevTools.ts patchright/node_modules/playwright-core/src/server/chromium/crDevTools.ts
---
+++
@@ -64,7 +64,6 @@
}).catch(e => null);
});
Promise.all([
- session.send('Runtime.enable'),
session.send('Runtime.addBinding', { name: kBindingName }),
session.send('Page.enable'),
session.send('Page.addScriptToEvaluateOnNewDocument', { source: `
diff -ruN -x protocol.yml --minimal playwright/node_modules/playwright-core/src/server/chromium/crNetworkManager.ts patchright/node_modules/playwright-core/src/server/chromium/crNetworkManager.ts
---
+++
@@ -30,7 +30,7 @@
import type * as types from '../types';
import type { CRPage } from './crPage';
import type { CRServiceWorker } from './crServiceWorker';
-
+import crypto from "crypto";
type SessionInfo = {
session: CRSession;
@@ -97,6 +97,7 @@
if (info)
eventsHelper.removeEventListeners(info.eventListeners);
this._sessions.delete(session);
+ if (!this._sessions.size) this._alreadyTrackedNetworkIds.clear();
}
private async _forEachSession(cb: (sessionInfo: SessionInfo) => Promise<any>) {
@@ -142,6 +143,10 @@
async setRequestInterception(value: boolean) {
this._userRequestInterceptionEnabled = value;
await this._updateProtocolRequestInterception();
+
+ if (this._page)
+ await this._forEachSession(info => info.session.send('Network.setCacheDisabled', { cacheDisabled: this._page.needsRequestInterception() }));
+
}
async _updateProtocolRequestInterception() {
@@ -156,7 +161,11 @@
const enabled = this._protocolRequestInterceptionEnabled;
if (initial && !enabled)
return;
- const cachePromise = info.session.send('Network.setCacheDisabled', { cacheDisabled: enabled });
+
+ const hasHarRecorders = !!this._page?.browserContext?._harRecorders?.size;
+ const userInterception = this._page ? this._page.needsRequestInterception() : false;
+ const cachePromise = info.session.send('Network.setCacheDisabled', { cacheDisabled: userInterception || hasHarRecorders });
+
let fetchPromise = Promise.resolve<any>(undefined);
if (!info.workerFrame) {
if (enabled)
@@ -238,6 +247,7 @@
}
_onRequestPaused(sessionInfo: SessionInfo, event: Protocol.Fetch.requestPausedPayload) {
+ if (this._alreadyTrackedNetworkIds.has(event.networkId)) return;
if (!event.networkId) {
// Fetch without networkId means that request was not recognized by inspector, and
// it will never receive Network.requestWillBeSent. Continue the request to not affect it.
@@ -276,6 +286,10 @@
}
_onRequest(requestWillBeSentSessionInfo: SessionInfo, requestWillBeSentEvent: Protocol.Network.requestWillBeSentPayload, requestPausedSessionInfo: SessionInfo | undefined, requestPausedEvent: Protocol.Fetch.requestPausedPayload | undefined) {
+
+ if (this._alreadyTrackedNetworkIds.has(requestWillBeSentEvent.requestId))
+ return;
+
if (requestWillBeSentEvent.request.url.startsWith('data:'))
return;
let redirectedFrom: InterceptableRequest | null = null;
@@ -287,6 +301,13 @@
redirectedFrom = request;
}
}
+ const isInterceptedOptionsPreflight = !!requestPausedEvent && requestPausedEvent.request.method === 'OPTIONS' && requestWillBeSentEvent.initiator.type === 'preflight';
+
+ if (isInterceptedOptionsPreflight && !(this._page || this._serviceWorker).needsRequestInterception()) {
+ requestPausedSessionInfo!.session._sendMayFail('Fetch.continueRequest', { requestId: requestPausedEvent!.requestId });
+ return;
+ }
+
let frame = requestWillBeSentEvent.frameId ? this._page?.frameManager.frame(requestWillBeSentEvent.frameId) : requestWillBeSentSessionInfo.workerFrame;
// Requests from workers lack frameId, because we receive Network.requestWillBeSent
// on the worker target. However, we receive Fetch.requestPaused on the page target,
@@ -306,7 +327,6 @@
// we accept all CORS options, assuming that this was intended when setting route.
//
// Note: it would be better to match the URL against interception patterns.
- const isInterceptedOptionsPreflight = !!requestPausedEvent && requestPausedEvent.request.method === 'OPTIONS' && requestWillBeSentEvent.initiator.type === 'preflight';
if (isInterceptedOptionsPreflight && (this._page || this._serviceWorker)!.needsRequestInterception()) {
const requestHeaders = requestPausedEvent.request.headers;
const responseHeaders: Protocol.Fetch.HeaderEntry[] = [
@@ -346,7 +366,7 @@
}
requestPausedSessionInfo!.session._sendMayFail('Fetch.continueRequest', { requestId: requestPausedEvent.requestId, headers: headersOverride });
} else {
- route = new RouteImpl(requestPausedSessionInfo!.session, requestPausedEvent.requestId);
+ route = new RouteImpl(requestPausedSessionInfo!.session, requestPausedEvent.requestId, this._page, requestPausedEvent.networkId ?? requestPausedEvent.requestId, this);
}
}
const isNavigationRequest = requestWillBeSentEvent.requestId === requestWillBeSentEvent.loaderId && requestWillBeSentEvent.type === 'Document';
@@ -558,6 +578,8 @@
if (request.session !== sessionInfo.session && !sessionInfo.isMain && (request._documentId === request._requestId || sessionInfo.workerFrame))
request.session = sessionInfo.session;
}
+
+ _alreadyTrackedNetworkIds: Set<string> = new Set();
}
class InterceptableRequest {
@@ -614,38 +636,148 @@
_alreadyContinuedParams: Protocol.Fetch.continueRequestParameters | undefined;
_fulfilled: boolean = false;
- constructor(session: CRSession, interceptionId: string) {
+ constructor(session: CRSession, interceptionId: string, page: Page | null, networkId: string, sessionManager: CRNetworkManager) {
+ this._page = void 0;
+ this._networkId = void 0;
+ this._sessionManager = void 0;
this._session = session;
this._interceptionId = interceptionId;
+ this._page = page;
+ this._networkId = networkId;
+ this._sessionManager = sessionManager;
+ eventsHelper.addEventListener(this._session, 'Fetch.requestPaused', async e => await this._networkRequestIntercepted(e));
}
async continue(overrides: types.NormalizedContinueOverrides): Promise<void> {
- this._alreadyContinuedParams = {
- requestId: this._interceptionId!,
- url: overrides.url,
- headers: overrides.headers,
- method: overrides.method,
- postData: overrides.postData ? overrides.postData.toString('base64') : undefined
- };
- await catchDisallowedErrors(async () => {
- await this._session.send('Fetch.continueRequest', this._alreadyContinuedParams);
- });
+ ;
+ this._alreadyContinuedParams = {
+ requestId: this._interceptionId,
+ url: overrides.url,
+ headers: overrides.headers,
+ method: overrides.method,
+ postData: overrides.postData?.toString('base64'),
+ };
+ if (overrides.url && (overrides.url === 'http://patchright-init-script-inject.internal/' || overrides.url === 'https://patchright-init-script-inject.internal/')) {
+ await catchDisallowedErrors(async () => {
+ this._sessionManager._alreadyTrackedNetworkIds.add(this._networkId);
+ try {
+ await this._session._sendMayFail('Fetch.continueRequest', { requestId: this._interceptionId, interceptResponse: true });
+ } catch (e) {
+ this._sessionManager._alreadyTrackedNetworkIds.delete(this._networkId);
+ throw e;
+ }
+ });
+ } else {
+ await catchDisallowedErrors(async () => {
+ await this._session._sendMayFail('Fetch.continueRequest', this._alreadyContinuedParams);
+ });
+ }
+
}
async fulfill(response: types.NormalizedFulfillResponse) {
- this._fulfilled = true;
- const body = response.isBase64 ? response.body : Buffer.from(response.body).toString('base64');
- const responseHeaders = splitSetCookieHeader(response.headers);
- await catchDisallowedErrors(async () => {
- await this._session.send('Fetch.fulfillRequest', {
- requestId: this._interceptionId!,
- responseCode: response.status,
- responsePhrase: network.statusText(response.status),
- responseHeaders,
- body,
- });
- });
+ const isTextHtml = response.headers.some((header) => header.name.toLowerCase() === "content-type" && header.value.includes("text/html"));
+ const pageDelegate = this._page?.delegate ?? null;
+ const initScriptTag = pageDelegate?.initScriptTag ?? "";
+ const allInjections = pageDelegate
+ ? [...pageDelegate._mainFrameSession._evaluateOnNewDocumentScripts]
+ : [];
+
+ if (isTextHtml && allInjections.length && initScriptTag) {
+ // Decode body if needed
+ if (response.isBase64) {
+ response.isBase64 = false;
+ response.body = Buffer.from(response.body, "base64").toString("utf-8");
+ }
+
+ // CSP Detection and Fixing
+ const cspHeaderNames = ["content-security-policy", "content-security-policy-report-only"];
+ const extractNonce = (cspValue) => {
+ const match = cspValue.match(/script-src[^;]*'nonce-([^'"s;]+)'/i);
+ return match?.[1] ?? null;
+ };
+ let useNonce = false;
+ let scriptNonce = null;
+
+ // Fix CSP in headers
+ for (const header of response.headers) {
+ if (cspHeaderNames.includes(header.name.toLowerCase())) {
+ const originalCsp = header.value ?? "";
+ // Extract nonce if present
+ const nonce = !useNonce && extractNonce(originalCsp);
+ if (nonce) {
+ scriptNonce = nonce;
+ useNonce = true;
+ }
+
+ header.value = this._fixCSP(originalCsp, scriptNonce);
+ }
+ }
+
+ // Fix CSP in meta tags
+ if (typeof response.body === "string" && response.body.length) {
+ response.body = response.body.replace(
+ /<meta[^>]*http-equiv=(?:"|')?Content-Security-Policy(?:"|')?[^>]*>/gi,
+ (match) => {
+ const contentMatch = match.match(/content=(?:"|')([^"']*)(?:"|')/i);
+ if (!contentMatch)
+ return match;
+
+ let originalCsp = contentMatch[1];
+ // Decode HTML entities
+ originalCsp = originalCsp
+ .replace(/&/g, '&') // Must be first!
+ .replace(/</g, '<')
+ .replace(/>/g, '>')
+ .replace(/"/g, '"')
+ .replace(/'/g, "'")
+ .replace(/"/g, '"')
+ .replace(/ /g, ' ')
+ .replace(/&#(d+);/g, (match, dec) => String.fromCharCode(dec))
+ .replace(/&#x([0-9a-fA-F]+);/g, (_, hex) => String.fromCharCode(parseInt(hex, 16)));
+
+ // Extract nonce if present
+ const nonce = !useNonce && extractNonce(originalCsp);
+ if (nonce) {
+ scriptNonce = nonce;
+ useNonce = true;
+ }
+
+ const fixedCsp = this._fixCSP(originalCsp, scriptNonce);
+ // Re-encode for HTML
+ const encodedCsp = fixedCsp.replace(/'/g, ''').replace(/"/g, '"');
+ return match.replace(contentMatch[1], encodedCsp);
+ }
+ );
+ }
+
+ // Build injection HTML - only use nonce if one was found in existing CSP
+ const nonceAttr = useNonce ? `nonce="${scriptNonce}"` : '';
+ let injectionHTML = "";
+ allInjections.forEach((script) => {