forked from microsoft/playwright-python
-
Notifications
You must be signed in to change notification settings - Fork 25
/
patchright_driver_patch.js
1232 lines (1164 loc) · 47.1 KB
/
patchright_driver_patch.js
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
import { Project, SyntaxKind, IndentationText } from "ts-morph";
const project = new Project({
manipulationSettings: {
indentationText: IndentationText.TwoSpaces,
},
});
// ----------------------------
// server/browserContext.ts
// ----------------------------
const browserContextSourceFile = project.addSourceFileAtPath(
"packages/playwright-core/src/server/browserContext.ts",
);
// ------- BrowserContext Class -------
const browserContextClass = browserContextSourceFile.getClass("BrowserContext");
// -- _initialize Method --
const initializeMethod = browserContextClass.getMethod("_initialize");
// Getting the service worker registration call
const initializeMethodCall = initializeMethod
.getDescendantsOfKind(SyntaxKind.CallExpression)
.find((call) => {
return (
call.getExpression().getText().includes("addInitScript") &&
call
.getArguments()
.some((arg) =>
arg.getText().includes("navigator.serviceWorker.register"),
)
);
});
// Replace the service worker registration call with a custom one, which is less obvious
initializeMethodCall
.getArguments()[0]
.replaceWithText("`navigator.serviceWorker.register = async () => { };`");
// -- exposeBinding Method --
const exposeBindingMethod = browserContextClass.getMethod("exposeBinding");
// Remove old loop and logic for localFrames and isolated world creation
exposeBindingMethod.getStatements().forEach((statement) => {
const text = statement.getText();
// Check if the statement matches the patterns
if (text.includes("this.doAddInitScript(binding.initScript)"))
statement.replaceWithText("await this.doExposeBinding(binding);");
else if (
text.includes("this.pages().map(page => page.frames()).flat()") ||
text.includes("frame.evaluateExpression(binding.initScript.source)")
)
statement.remove();
});
// -- _removeExposedBindings Method --
const removeExposedBindingsMethod = browserContextClass.getMethod(
"_removeExposedBindings",
);
removeExposedBindingsMethod.setBodyText(`for (const key of this._pageBindings.keys()) {
if (!key.startsWith('__pw'))
this._pageBindings.delete(key);
}
await this.doRemoveExposedBindings();`);
// -- _removeInitScripts Method --
const removeInitScriptsMethod =
browserContextClass.getMethod("_removeInitScripts");
removeInitScriptsMethod.setBodyText(`this.initScripts.splice(0, this.initScripts.length);
await this.doRemoveInitScripts();`);
// ----------------------------
// server/chromium/chromium.ts
// ----------------------------
const chromiumSourceFile = project.addSourceFileAtPath(
"packages/playwright-core/src/server/chromium/chromium.ts",
);
// ------- Chromium Class -------
const chromiumClass = chromiumSourceFile.getClass("Chromium");
// -- _innerDefaultArgs Method --
const innerDefaultArgsMethod = chromiumClass.getMethod("_innerDefaultArgs");
// Get all the if statements in the method
const innerDefaultArgsMethodStatements =
innerDefaultArgsMethod.getDescendantsOfKind(SyntaxKind.IfStatement);
// Modifying the Code to always use the --headless=new flag
innerDefaultArgsMethodStatements.forEach((ifStatement) => {
const condition = ifStatement.getExpression().getText();
if (condition.includes("process.env.PLAYWRIGHT_CHROMIUM_USE_HEADLESS_NEW")) {
ifStatement.replaceWithText("chromeArguments.push('--headless=new');");
}
});
// ----------------------------
// server/chromium/chromiumSwitches.ts
// ----------------------------
const chromiumSwitchesSourceFile = project.addSourceFileAtPath(
"packages/playwright-core/src/server/chromium/chromiumSwitches.ts",
);
// -- chromiumSwitches Array Variable --
const chromiumSwitchesArray = chromiumSwitchesSourceFile
.getVariableDeclarationOrThrow("chromiumSwitches")
.getInitializerIfKindOrThrow(SyntaxKind.ArrayLiteralExpression);
const switchesToDisable = [
"'--enable-automation'",
"'--disable-popup-blocking'",
"'--disable-component-update'",
"'--disable-default-apps'",
"'--disable-extensions'",
"'--disable-client-side-phishing-detection'",
"'--disable-component-extensions-with-background-pages'",
"'--allow-pre-commit-input'",
"'--disable-ipc-flooding-protection'",
"'--metrics-recording-only'",
"'--unsafely-disable-devtools-self-xss-warnings'",
"'--disable-back-forward-cache'",
"'--disable-features=ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroyProfileOnBrowserClose,MediaRouter,DialMediaRouteProvider,AcceptCHFrame,AutoExpandDetailsElement,CertificateTransparencyComponentUpdater,AvoidUnnecessaryBeforeUnloadCheckSync,Translate,HttpsUpgrades,PaintHolding,ThirdPartyStoragePartitioning,LensOverlay,PlzDedicatedWorker'"
];
chromiumSwitchesArray.getElements().forEach((element) => {
if (switchesToDisable.includes(element.getText())) {
chromiumSwitchesArray.removeElement(element);
}
});
// Add custom switches to the array
chromiumSwitchesArray.addElement(
`'--disable-blink-features=AutomationControlled'`,
);
// ----------------------------
// server/chromium/crBrowser.ts
// ----------------------------
const crBrowserSourceFile = project.addSourceFileAtPath(
"packages/playwright-core/src/server/chromium/crBrowser.ts",
);
// ------- CRDevTools Class -------
const crBrowserContextClass = crBrowserSourceFile.getClass("CRBrowserContext");
// -- doRemoveNonInternalInitScripts Method --
crBrowserContextClass.getMethod("doRemoveNonInternalInitScripts").remove();
// -- doRemoveInitScripts Method --
// crBrowserContextClass.addMethod({
// name: "doRemoveInitScripts",
// scope: "protected",
// isAbstract: true,
// returnType: "Promise<void>",
// });
// -- doExposeBinding Method --
//crBrowserContextClass.addMethod({
// name: "doExposeBinding",
// scope: "protected",
// isAbstract: true,
// parameters: [{ name: "binding", type: "PageBinding" }],
// returnType: "Promise<void>",
//});
// -- doRemoveExposedBindings Method --
//crBrowserContextClass.addMethod({
// name: "doRemoveExposedBindings",
// scope: "protected",
// isAbstract: true,
// returnType: "Promise<void>",
//});
// -- doRemoveInitScripts Method --
crBrowserContextClass.addMethod({
name: "doRemoveInitScripts",
isAsync: true,
});
const doRemoveInitScriptsMethod = crBrowserContextClass.getMethod(
"doRemoveInitScripts",
);
doRemoveInitScriptsMethod.setBodyText(
`for (const page of this.pages()) await (page._delegate as CRPage).removeInitScripts();`,
);
// ------- Class -------
const crBrowserClass = crBrowserSourceFile.getClass("CRBrowserContext");
// -- doExposeBinding Method --
crBrowserClass.addMethod({
name: "doExposeBinding",
isAsync: true,
parameters: [{ name: "binding", type: "PageBinding" }],
});
const doExposeBindingMethod = crBrowserClass.getMethod("doExposeBinding");
doExposeBindingMethod.setBodyText(
`for (const page of this.pages()) await (page._delegate as CRPage).exposeBinding(binding);`,
);
// -- doRemoveExposedBindings Method --
crBrowserClass.addMethod({
name: "doRemoveExposedBindings",
isAsync: true,
});
const doRemoveExposedBindingsMethod = crBrowserClass.getMethod(
"doRemoveExposedBindings",
);
doRemoveExposedBindingsMethod.setBodyText(
`for (const page of this.pages()) await (page._delegate as CRPage).removeExposedBindings();`,
);
// ----------------------------
// server/chromium/crDevTools.ts
// ----------------------------
const crDevToolsSourceFile = project.addSourceFileAtPath(
"packages/playwright-core/src/server/chromium/crDevTools.ts",
);
// ------- CRDevTools Class -------
const crDevToolsClass = crDevToolsSourceFile.getClass("CRDevTools");
// -- Install Method --
const installMethod = crDevToolsClass.getMethod("install");
// Find the specific `Promise.all` call
const promiseAllCalls = installMethod
.getDescendantsOfKind(SyntaxKind.CallExpression)
.filter((call) => call.getExpression().getText() === "Promise.all");
// Removing Runtime.enable from the Promise.all call
promiseAllCalls.forEach((call) => {
const arrayLiteral = call.getFirstDescendantByKind(
SyntaxKind.ArrayLiteralExpression,
);
if (arrayLiteral) {
arrayLiteral.getElements().forEach((element) => {
if (element.getText().includes("session.send('Runtime.enable'")) {
arrayLiteral.removeElement(element);
}
});
}
});
// ----------------------------
// server/chromium/crNetworkManager.ts
// ----------------------------
const crNetworkManagerSourceFile = project.addSourceFileAtPath(
"packages/playwright-core/src/server/chromium/crNetworkManager.ts",
);
// Add the custom import and comment at the start of the file
crNetworkManagerSourceFile.insertStatements(0, [
"// undetected-undetected_playwright-patch - custom imports",
"import crypto from 'crypto';",
"",
]);
// ------- CRNetworkManager Class -------
const crNetworkManagerClass =
crNetworkManagerSourceFile.getClass("CRNetworkManager");
// -- _onRequest Method --
const onRequestMethod = crNetworkManagerClass.getMethod("_onRequest");
// Find the assignment statement you want to modify
const routeAssignment = onRequestMethod
.getDescendantsOfKind(SyntaxKind.BinaryExpression)
.find((expr) =>
expr
.getText()
.includes(
"route = new RouteImpl(requestPausedSessionInfo!.session, requestPausedEvent.requestId)",
),
);
// Adding new parameter to the RouteImpl call
if (routeAssignment) {
routeAssignment
.getRight()
.replaceWithText(
"new RouteImpl(requestPausedSessionInfo!.session, requestPausedEvent.requestId, this._page)",
);
}
// ------- RouteImpl Class -------
const routeImplClass = crNetworkManagerSourceFile.getClass("RouteImpl");
// -- RouteImpl Constructor --
const constructorDeclaration = routeImplClass
.getConstructors()
.find((ctor) =>
ctor
.getText()
.includes("constructor(session: CRSession, interceptionId: string)"),
);
if (constructorDeclaration) {
// Get current parameters and add the new `page` parameter
const parameters = constructorDeclaration.getParameters();
// Adding the 'page' parameter
constructorDeclaration.insertParameter(parameters.length, {
name: "page",
type: "Page", // Replace with the actual type of 'page' if different
});
// Modify the constructor's body to include `this._page = page;`
const body = constructorDeclaration.getBody();
// Insert `this._page = void 0;`
body.insertStatements(0, "this._page = void 0;");
// Insert `this._page = page;` at the end of the constructor body
body.addStatements("this._page = page;");
// Inject HTML code
const fulfillMethod = routeImplClass.getMethodOrThrow("fulfill");
const methodBody = fulfillMethod.getBodyOrThrow();
// Insert the custom code at the beginning of the `fulfill` method
const customHTMLInjectCode = `const isTextHtml = response.headers.some(header => header.name === 'content-type' && header.value.includes('text/html'));
var allInjections = [...this._page._delegate._mainFrameSession._evaluateOnNewDocumentScripts];
for (const binding of this._page._delegate._browserContext._pageBindings.values()) {
if (!allInjections.includes(binding)) allInjections.push(binding);
}
if (isTextHtml && allInjections.length) {
// I Chatted so hard for this Code
let scriptNonce = crypto.randomBytes(22).toString('hex');
for (let i = 0; i < response.headers.length; i++) {
if (response.headers[i].name === 'content-security-policy' || response.headers[i].name === 'content-security-policy-report-only') {
// Search for an existing script-src nonce that we can hijack
let cspValue = response.headers[i].value;
const nonceRegex = /script-src[^;]*'nonce-([\\w-]+)'/;
const nonceMatch = cspValue.match(nonceRegex);
if (nonceMatch) {
scriptNonce = nonceMatch[1];
} else {
// Add the new nonce value to the script-src directive
const scriptSrcRegex = /(script-src[^;]*)(;|$)/;
const newCspValue = cspValue.replace(scriptSrcRegex, \`$1 'nonce-\${scriptNonce}'$2\`);
response.headers[i].value = newCspValue;
}
break;
}
}
let injectionHTML = "";
allInjections.forEach((script) => {
injectionHTML += \`<script class="\${this._page._delegate.initScriptTag}" nonce="\${scriptNonce}" type="text/javascript">\${script.source}</script>\`;
});
if (response.isBase64) {
response.isBase64 = false;
response.body = injectionHTML + Buffer.from(response.body, 'base64').toString('utf-8');
} else {
response.body = injectionHTML + response.body;
}
}`;
methodBody.insertStatements(0, customHTMLInjectCode);
}
// ----------------------------
// server/chromium/crServiceWorker.ts
// ----------------------------
const crServiceWorkerSourceFile = project.addSourceFileAtPath(
"packages/playwright-core/src/server/chromium/crServiceWorker.ts",
);
// ------- CRServiceWorker Class -------
const crServiceWorkerClass =
crServiceWorkerSourceFile.getClass("CRServiceWorker");
// -- CRServiceWorker Constructor --
const crServiceWorkerConstructorDeclaration = crServiceWorkerClass
.getConstructors()
.find((ctor) =>
ctor
.getText()
.includes(
"constructor(browserContext: CRBrowserContext, session: CRSession, url: string)",
),
);
const crServiceWorkerConstructorBody =
crServiceWorkerConstructorDeclaration.getBody();
// Find the Runtime.enable statement to remove
const statementToRemove = crServiceWorkerConstructorBody
.getStatements()
.find((statement) =>
statement
.getText()
.includes("session.send('Runtime.enable', {}).catch(e => { });"),
);
if (statementToRemove) statementToRemove.remove();
// ----------------------------
// server/frames.ts
// ----------------------------
const framesSourceFile = project.addSourceFileAtPath(
"packages/playwright-core/src/server/frames.ts",
);
// Add the custom import and comment at the start of the file
framesSourceFile.insertStatements(0, [
"// undetected-undetected_playwright-patch - custom imports",
"import { CRExecutionContext } from './chromium/crExecutionContext';",
"import { FrameExecutionContext } from './dom';",
"import crypto from 'crypto';",
"",
]);
// ------- Frame Class -------
const frameClass = framesSourceFile.getClass("Frame");
// Add Properties to the Frame Class
frameClass.addProperty({
name: "_isolatedWorld",
type: "dom.FrameExecutionContext",
});
frameClass.addProperty({
name: "_mainWorld",
type: "dom.FrameExecutionContext",
});
frameClass.addProperty({
name: "_iframeWorld",
type: "dom.FrameExecutionContext",
});
// -- _onClearLifecycle Method --
const onClearLifecycleMethod = frameClass.getMethod("_onClearLifecycle");
// Modify the constructor's body to include unassignments
const onClearLifecycleBody = onClearLifecycleMethod.getBody();
onClearLifecycleBody.insertStatements(0, "this._iframeWorld = undefined;");
onClearLifecycleBody.insertStatements(0, "this._mainWorld = undefined;");
onClearLifecycleBody.insertStatements(0, "this._isolatedWorld = undefined;");
// -- _getFrameMainFrameContextId Method --
// Define the getFrameMainFrameContextIdCode
const getFrameMainFrameContextIdCode = `var globalDocument = await client._sendMayFail('DOM.getFrameOwner', { frameId: this._id });
if (globalDocument && globalDocument.nodeId) {
for (const executionContextId of this._page._delegate._sessionForFrame(this)._parsedExecutionContextIds) {
var documentObj = await client._sendMayFail("DOM.resolveNode", { nodeId: globalDocument.nodeId });
if (documentObj) {
var globalThis = await client._sendMayFail('Runtime.evaluate', {
expression: "document",
serializationOptions: { serialization: "idOnly" },
contextId: executionContextId
});
if (globalThis) {
var globalThisObjId = globalThis["result"]['objectId'];
var requestedNode = await client.send("DOM.requestNode", { objectId: globalThisObjId });
var node = await client._sendMayFail("DOM.describeNode", { nodeId: requestedNode.nodeId, pierce: true, depth: 10 });
if (node && node.node.documentURL == this._url) {
var node0 = await client._sendMayFail("DOM.resolveNode", { nodeId: requestedNode.nodeId });
if (node0 && (node.node.nodeId - 1 == globalDocument.nodeId)) { // && (node.node.backendNodeId + 1 == globalDocument.backendNodeId)
var _executionContextId = parseInt(node0.object.objectId.split('.')[1], 10);
return _executionContextId;
}
}
}
}
}
}
return 0;`;
// Add the method to the class
frameClass.addMethod({
name: "_getFrameMainFrameContextId",
isAsync: true,
parameters: [
{
name: "client",
},
],
returnType: "Promise<number>",
});
const getFrameMainFrameContextIdMethod = frameClass.getMethod(
"_getFrameMainFrameContextId",
);
getFrameMainFrameContextIdMethod.setBodyText(
getFrameMainFrameContextIdCode.trim(),
);
// -- _context Method --
const contextMethodCode = `
await this._page._delegate._mainFrameSession._client._sendMayFail('DOM.enable');
var globalDoc = await this._page._delegate._mainFrameSession._client._sendMayFail('DOM.getFrameOwner', { frameId: this._id });
if (globalDoc) {
await this._page._delegate._mainFrameSession._client._sendMayFail("DOM.resolveNode", { nodeId: globalDoc.nodeId })
}
if (this.isDetached()) throw new Error('Frame was detached');
try {
var client = this._page._delegate._sessionForFrame(this)._client
} catch (e) { var client = this._page._delegate._mainFrameSession._client }
var iframeExecutionContextId = await this._getFrameMainFrameContextId(client)
if (world == "main") {
// Iframe Only
if (this != this._page.mainFrame() && iframeExecutionContextId && this._iframeWorld == undefined) {
var executionContextId = iframeExecutionContextId
var crContext = new CRExecutionContext(client, { id: executionContextId }, this._id)
this._iframeWorld = new FrameExecutionContext(crContext, this, world)
this._page._delegate._mainFrameSession._onExecutionContextCreated({
id: executionContextId, origin: world, name: world, auxData: { isDefault: this === this._page.mainFrame(), type: 'isolated', frameId: this._id }
})
} else if (this._mainWorld == undefined) {
var globalThis = await client._sendMayFail('Runtime.evaluate', {
expression: "globalThis",
serializationOptions: { serialization: "idOnly" }
});
if (!globalThis) { return }
var globalThisObjId = globalThis["result"]['objectId']
var executionContextId = parseInt(globalThisObjId.split('.')[1], 10);
var crContext = new CRExecutionContext(client, { id: executionContextId }, this._id)
this._mainWorld = new FrameExecutionContext(crContext, this, world)
this._page._delegate._mainFrameSession._onExecutionContextCreated({
id: executionContextId, origin: world, name: world, auxData: { isDefault: this === this._page.mainFrame(), type: 'isolated', frameId: this._id }
})
}
}
if (world != "main" && this._isolatedWorld == undefined) {
world = "utility"
var result = await client._sendMayFail('Page.createIsolatedWorld', {
frameId: this._id, grantUniveralAccess: true, worldName: world
});
if (!result) { return }
var executionContextId = result.executionContextId
var crContext = new CRExecutionContext(client, { id: executionContextId }, this._id)
this._isolatedWorld = new FrameExecutionContext(crContext, this, world)
this._page._delegate._mainFrameSession._onExecutionContextCreated({
id: executionContextId, origin: world, name: world, auxData: { isDefault: this === this._page.mainFrame(), type: 'isolated', frameId: this._id }
})
}
if (world != "main") {
return this._isolatedWorld;
} else if (this != this._page.mainFrame() && iframeExecutionContextId) {
return this._iframeWorld;
} else {
return this._mainWorld;
}`;
const contextMethod = frameClass.getMethod("_context");
contextMethod.setIsAsync(true);
contextMethod.setBodyText(contextMethodCode.trim());
// -- _setContext Method --
const setContentMethod = frameClass.getMethod("setContent");
// Locate the existing line of code
const existingLine = setContentMethod
.getDescendantsOfKind(SyntaxKind.VariableDeclaration)
.find((variableDeclaration) =>
variableDeclaration
.getText()
.includes(
"--playwright--set--content--${this._id}--${++this._setContentCounter}--`",
),
);
// Get the position to insert the new line after
const position = existingLine.getEnd();
// Insert the new line after the existing line
setContentMethod.insertText(
position + 1,
"\n const bindingName = \"_tagDebug\" + crypto.randomBytes(20).toString('hex');",
);
// Find the evaluate call expression
const evaluateCall = setContentMethod
.getDescendantsOfKind(SyntaxKind.CallExpression)
.find(
(callExpr) => callExpr.getExpression().getText() === "context.evaluate",
);
if (evaluateCall) {
const arrowFunction = evaluateCall.getArguments()[0];
const objectArg = evaluateCall.getArguments()[1];
// Ensure the arrow function and object argument are what we expect
if (
arrowFunction?.getKind() === SyntaxKind.ArrowFunction &&
objectArg?.getKind() === SyntaxKind.ObjectLiteralExpression
) {
const arrowFunctionBody = arrowFunction.getBody();
if (arrowFunctionBody?.getKind() === SyntaxKind.Block) {
const block = arrowFunctionBody.asKind(SyntaxKind.Block);
if (block) {
// Add the new lines after document.open();
block.insertStatements(1, [
"var _tagDebug = window[bindingName].bind({});",
"delete window[bindingName]",
'_tagDebug(\'{ "name": "\' + bindingName + \'", "seq": 1, "serializedArgs": ["\' + tag + \'"] }\');',
]);
// Replace the destructured parameters in the arrow function
const paramsText = arrowFunction.getParameters()[0].getText();
const updatedParamsText = paramsText.replace(
"{ html, tag }",
"{ html, tag, bindingName }",
);
arrowFunction.getParameters()[0].replaceWithText(updatedParamsText);
// Add bindingName to the object literal passed to evaluate
objectArg.addProperty("bindingName");
}
}
}
}
const oldCode = `const lifecyclePromise = new Promise((resolve, reject) => {
this._page._frameManager._consoleMessageTags.set(tag, () => {
// Clear lifecycle right after document.open() - see 'tag' below.
this._onClearLifecycle();
this._waitForLoadState(progress, waitUntil).then(resolve).catch(reject);
});
});`.replace(/ +/g, "");
const newCode = ` await this._page._delegate._mainFrameSession._client.send('Runtime.addBinding', { name: bindingName });
const lifecyclePromise = new Promise(async (resolve, reject) => {
await this._page.exposeBinding(bindingName, false, (tag) => {
this._onClearLifecycle();
this._waitForLoadState(progress, waitUntil).then(resolve).catch(reject);
});
});`;
// Get the method's text and replace old code with new code
const methodText = setContentMethod.getText();
const unindentedMethodText = setContentMethod.getText().replace(/ +/g, "");
const updatedText = unindentedMethodText.replace(oldCode, newCode);
let newMethodText = "";
// Iterate through each line of the method's text and get the same line from the updated text
methodText.split("\n").forEach((line, index) => {
const updatedLine = updatedText.split("\n")[index];
if (line.replace(/ +/g, "") != updatedLine) {
// If the lines are different, add the updated line to the new method text
newMethodText += updatedLine + "\n";
} else {
// Otherwise, add the original line to the new method text
newMethodText += line + "\n";
}
});
// Update the method's text
setContentMethod.replaceWithText(newMethodText);
// ----------------------------
// server/chromium/crPage.ts
// ----------------------------
const crPageSourceFile = project.addSourceFileAtPath(
"packages/playwright-core/src/server/chromium/crPage.ts",
);
// Add the custom import and comment at the start of the file
crPageSourceFile.insertStatements(0, [
"// undetected-undetected_playwright-patch - custom imports",
"import crypto from 'crypto';",
"",
]);
// ------- CRPage Class -------
const crPageClass = crPageSourceFile.getClass("CRPage");
// -- CRPage Constructor --
const crPageConstructor = crPageClass
.getConstructors()
.find((ctor) =>
ctor
.getText()
.includes(
"constructor(client: CRSession, targetId: string, browserContext: CRBrowserContext, opener: CRPage | null",
),
);
const statementToReplace = crPageConstructor
.getStatements()
.find(
(statement) => statement.getText() === "this.updateRequestInterception();",
);
if (statementToReplace) {
// Replace the statement with the new code
statementToReplace.replaceWithText(`this._networkManager.setRequestInterception(true);
this.initScriptTag = "injected-playwright-init-script-" + crypto.randomBytes(20).toString('hex');`);
}
// -- exposeBinding Method --
crPageClass.addMethod({
name: "exposeBinding",
isAsync: true,
parameters: [
{
name: "binding",
},
],
});
const crExposeBindingMethod = crPageClass.getMethod("exposeBinding");
crExposeBindingMethod.setBodyText(
`await this._forAllFrameSessions(frame => frame._initBinding(binding));
await Promise.all(this._page.frames().map(frame => frame.evaluateExpression(binding.source).catch(e => {})));`,
);
// -- removeExposedBindings Method --
crPageClass.addMethod({
name: "removeExposedBindings",
isAsync: true,
});
const crRemoveExposedBindingsMethod = crPageClass.getMethod(
"removeExposedBindings",
);
crRemoveExposedBindingsMethod.setBodyText(
`await this._forAllFrameSessions(frame => frame._removeExposedBindings());`,
);
// -- removeNonInternalInitScripts Method --
crPageClass
.getMethod("removeNonInternalInitScripts")
.rename("removeInitScripts");
// -- addInitScript Method --
const addInitScriptMethod = crPageClass.getMethod("addInitScript");
const addInitScriptMethodBody = addInitScriptMethod.getBody();
// Insert a new line of code before the first statement
addInitScriptMethodBody.insertStatements(
0,
"this._page.initScripts.push(initScript);",
);
// ------- FrameSession Class -------
const frameSessionClass = crPageSourceFile.getClass("FrameSession");
// Add Properties to the Frame Class
frameSessionClass.addProperty({
name: "_exposedBindingNames",
type: "string[]",
initializer: "[]",
});
frameSessionClass.addProperty({
name: "_evaluateOnNewDocumentScripts",
type: "string[]",
initializer: "[]",
});
frameSessionClass.addProperty({
name: "_parsedExecutionContextIds",
type: "number[]",
initializer: "[]",
});
frameSessionClass.addProperty({
name: "_exposedBindingScripts",
type: "string[]",
initializer: "[]",
});
const evaluateOnNewDocumentIdentifiers = frameSessionClass.getProperty(
"_evaluateOnNewDocumentIdentifiers",
);
// if (evaluateOnNewDocumentIdentifiers) evaluateOnNewDocumentIdentifiers.remove();
// -- _addRendererListeners Method --
const addRendererListenersMethod = frameSessionClass.getMethod(
"_addRendererListeners",
);
const addRendererListenersMethodBody = addRendererListenersMethod.getBody();
// Insert a new line of code before the first statement
addRendererListenersMethodBody.insertStatements(
0,
`this._client._sendMayFail("Debugger.enable", {});
eventsHelper.addEventListener(this._client, 'Debugger.scriptParsed', event => {
if (!this._parsedExecutionContextIds.includes(event.executionContextId)) this._parsedExecutionContextIds.push(event.executionContextId);
})`,
);
// -- _initialize Method --
const initializeFrameSessionMethod = frameSessionClass.getMethod("_initialize");
const initializeFrameSessionMethodBody = initializeFrameSessionMethod.getBody();
// Find the variable declaration
const variableName = "promises"; // The name of the variable to find
const variableDeclaration =
initializeFrameSessionMethod.getVariableDeclarationOrThrow(variableName);
// Find the initializer array
const initializer = variableDeclaration.getInitializerIfKindOrThrow(
SyntaxKind.ArrayLiteralExpression,
);
// Find the relevant element inside the array that we need to update
initializer.getElements().forEach((element) => {
if (
element.getText().includes("this._client.send('Runtime.enable'") ||
element
.getText()
.includes(
"this._client.send('Runtime.addBinding', { name: PageBinding.kPlaywrightBinding })",
)
) {
initializer.removeElement(element);
}
});
// Find the relevant element inside the array that we need to update
const pageGetFrameTreeCall = initializer
.getElements()
.find((element) =>
element.getText().startsWith("this._client.send('Page.getFrameTree'"),
);
if (
pageGetFrameTreeCall &&
pageGetFrameTreeCall.isKind(SyntaxKind.CallExpression)
) {
const thenBlock = pageGetFrameTreeCall
.asKindOrThrow(SyntaxKind.CallExpression)
.getFirstDescendantByKindOrThrow(SyntaxKind.ArrowFunction)
.getBody()
.asKindOrThrow(SyntaxKind.Block);
// Remove old loop and logic for localFrames and isolated world creation
const statementsToRemove = thenBlock
.getStatements()
.filter(
(statement) =>
statement
.getText()
.includes(
"const localFrames = this._isMainFrame() ? this._page.frames()",
) ||
statement
.getText()
.includes("this._client._sendMayFail('Page.createIsolatedWorld', {"),
);
statementsToRemove.forEach((statement) => statement.remove());
// Find the IfStatement that contains the "else" block
const ifStatement = thenBlock
.getStatements()
.find(
(statement) =>
statement.isKind(SyntaxKind.IfStatement) &&
statement.getText().includes("Page.lifecycleEvent"),
);
if (ifStatement && ifStatement.isKind(SyntaxKind.IfStatement)) {
const elseStatement = ifStatement.getElseStatement();
elseStatement.insertStatements(
0,
`const localFrames = this._isMainFrame() ? this._page.frames() : [this._page._frameManager.frame(this._targetId)!];
for (const frame of localFrames) {
this._page._frameManager.frame(frame._id)._context("utility");
for (const binding of this._crPage._browserContext._pageBindings.values())
frame.evaluateExpression(binding.source).catch(e => {});
for (const source of this._crPage._browserContext.initScripts)
frame.evaluateExpression(source).catch(e => {});
}`,
);
}
}
// Find the initScript Evaluation Loop
initializeFrameSessionMethodBody
.getDescendantsOfKind(SyntaxKind.ForOfStatement)
.forEach((statement) => {
if (statement.getText().includes("this._crPage._page.allInitScripts()")) {
if (
statement
.getText()
.includes("frame.evaluateExpression(initScript.source)")
) {
statement.replaceWithText(`for (const binding of this._crPage._browserContext._pageBindings.values()) frame.evaluateExpression(binding.source).catch(e => {});
for (const initScript of this._crPage._browserContext.initScripts) frame.evaluateExpression(initScript.source).catch(e => {});`);
} else if (
statement
.getText()
.includes("this._evaluateOnNewDocument(initScript, 'main')")
) {
statement.replaceWithText(`for (const binding of this._crPage._page.allBindings()) promises.push(this._initBinding(binding));
for (const initScript of this._crPage._browserContext.initScripts) promises.push(this._evaluateOnNewDocument(initScript, 'main'));
for (const initScript of this._crPage._page.initScripts) promises.push(this._evaluateOnNewDocument(initScript, 'main'));`);
}
}
});
// Find the statement `promises.push(this._client.send('Runtime.runIfWaitingForDebugger'))`
const promisePushStatements = initializeFrameSessionMethodBody
.getStatements()
.filter((statement) =>
statement
.getText()
.includes(
"promises.push(this._client.send('Runtime.runIfWaitingForDebugger'))",
),
);
// Ensure the right statements were found
if (promisePushStatements.length === 1) {
const [firstStatement] = promisePushStatements;
// Replace the first `promises.push` statement with the new conditional code
firstStatement.replaceWithText(
`if (!(this._crPage._page._pageBindings.size || this._crPage._browserContext._pageBindings.size)) promises.push(this._client.send('Runtime.runIfWaitingForDebugger'));`,
);
initializeFrameSessionMethodBody.addStatements(
`if (this._crPage._page._pageBindings.size || this._crPage._browserContext._pageBindings.size) await this._client.send('Runtime.runIfWaitingForDebugger');`,
);
}
// -- _initBinding Method --
frameSessionClass.addMethod({
name: "_initBinding",
isAsync: true,
parameters: [
{
name: "binding",
initializer: "PageBinding",
},
],
});
const initBindingMethod = frameSessionClass.getMethod("_initBinding");
initBindingMethod.setBodyText(`var result = await this._client._sendMayFail('Page.createIsolatedWorld', {
frameId: this._targetId, grantUniveralAccess: true, worldName: "utility"
});
if (!result) return
var isolatedContextId = result.executionContextId
var globalThis = await this._client._sendMayFail('Runtime.evaluate', {
expression: "globalThis",
serializationOptions: { serialization: "idOnly" }
});
if (!globalThis) return
var globalThisObjId = globalThis["result"]['objectId']
var mainContextId = parseInt(globalThisObjId.split('.')[1], 10);
await Promise.all([
this._client._sendMayFail('Runtime.addBinding', { name: binding.name }),
this._client._sendMayFail('Runtime.addBinding', { name: binding.name, executionContextId: mainContextId }),
this._client._sendMayFail('Runtime.addBinding', { name: binding.name, executionContextId: isolatedContextId }),
// this._client._sendMayFail("Runtime.evaluate", { expression: binding.source, contextId: mainContextId, awaitPromise: true })
]);
this._exposedBindingNames.push(binding.name);
this._exposedBindingScripts.push(binding.source);
await this._crPage.addInitScript(binding.source);
//this._client._sendMayFail('Runtime.runIfWaitingForDebugger')`);
// initBindingMethod.setBodyText(`const [, response] = await Promise.all([
// this._client.send('Runtime.addBinding', { name: binding.name }),
// this._client.send('Page.addScriptToEvaluateOnNewDocument', { source: binding.source })
// ]);
// this._exposedBindingNames.push(binding.name);
// if (!binding.name.startsWith('__pw'))
// this._evaluateOnNewDocumentIdentifiers.push(response.identifier);`);
// -- _removeExposedBindings Method --
frameSessionClass.addMethod({
name: "_removeExposedBindings",
isAsync: true,
});
const fsRemoveExposedBindingsMethod = frameSessionClass.getMethod(
"_removeExposedBindings",
);
fsRemoveExposedBindingsMethod.setBodyText(`const toRetain: string[] = [];
const toRemove: string[] = [];
for (const name of this._exposedBindingNames)
(name.startsWith('__pw_') ? toRetain : toRemove).push(name);
this._exposedBindingNames = toRetain;
await Promise.all(toRemove.map(name => this._client.send('Runtime.removeBinding', { name })));`);
// -- _navigate Method --
const navigateMethod = frameSessionClass.getMethod("_navigate");
const navigateMethodBody = navigateMethod.getBody();
// Insert the new line of code after the responseAwaitStatement
navigateMethodBody.insertStatements(
1,
`this._client._sendMayFail('Page.waitForDebugger');`,
);
// -- _onLifecycleEvent & _onFrameNavigated Method --
for (const methodName of ["_onLifecycleEvent", "_onFrameNavigated"]) {
const frameSessionMethod = frameSessionClass.getMethod(methodName);
const frameSessionMethodBody = frameSessionMethod.getBody();
frameSessionMethod.setIsAsync(true);
frameSessionMethodBody.addStatements(`var document = await this._client._sendMayFail("DOM.getDocument");
if (!document) return
var query = await this._client._sendMayFail("DOM.querySelectorAll", {
nodeId: document.root.nodeId,
selector: "[class=" + this._crPage.initScriptTag + "]"
});
if (!query) return
for (const nodeId of query.nodeIds) await this._client._sendMayFail("DOM.removeNode", { nodeId: nodeId });
await this._client._sendMayFail('Runtime.runIfWaitingForDebugger');
// ensuring execution context
try { await this._page._frameManager.frame(this._targetId)._context("utility") } catch { };`);
}
// -- _onExecutionContextCreated Method --
const onExecutionContextCreatedMethod = frameSessionClass.getMethod(
"_onExecutionContextCreated",
);
const onExecutionContextCreatedMethodBody =
onExecutionContextCreatedMethod.getBody();
onExecutionContextCreatedMethodBody.insertStatements(
0,
`for (const name of this._exposedBindingNames) this._client._sendMayFail('Runtime.addBinding', { name: name, executionContextId: contextPayload.id });`,
);
onExecutionContextCreatedMethodBody.insertStatements(
2,
`if (contextPayload.auxData.type == "worker") throw new Error("ExecutionContext is worker");`,
);
// Locate the statements you want to replace
const statementsToRemove = onExecutionContextCreatedMethod
.getStatements()
.filter((statement) => {
const text = statement.getText();
return (
text.includes("let worldName: types.World") ||
text.includes(
"if (contextPayload.auxData && !!contextPayload.auxData.isDefault)",
) ||
text.includes("worldName = 'main'") ||
text.includes("else if (contextPayload.name === UTILITY_WORLD_NAME)") ||
text.includes("worldName = 'utility'")
);
});
// If the statements are found, remove them
statementsToRemove.forEach((statement) => {
if (statement == statementsToRemove[0])
statement.replaceWithText("let worldName = contextPayload.name;");
else statement.remove();
});
onExecutionContextCreatedMethodBody.addStatements(
`for (const source of this._exposedBindingScripts) {
this._client._sendMayFail("Runtime.evaluate", {
expression: source,
contextId: contextPayload.id,
awaitPromise: true,
})
}`,
);
// -- _onAttachedToTarget Method --
const onAttachedToTargetMethod = frameSessionClass.getMethod(
"_onAttachedToTarget",
);
onAttachedToTargetMethod.setIsAsync(true);
const onAttachedToTargetMethodBody = onAttachedToTargetMethod.getBody();
// Find the specific line of code after which to insert the new code
const sessionOnceCall = onAttachedToTargetMethod
.getDescendantsOfKind(SyntaxKind.ExpressionStatement)
.find((statement) =>
statement
.getText()
.includes("session.once('Runtime.executionContextCreated'"),
);
// Insert the new lines of code after the found line
const block = sessionOnceCall.getParentIfKindOrThrow(SyntaxKind.Block);
block.insertStatements(sessionOnceCall.getChildIndex() + 1, [
`var globalThis = await session._sendMayFail('Runtime.evaluate', {`,
` expression: "globalThis",`,
` serializationOptions: { serialization: "idOnly" }`,
`});`,
`if (globalThis && globalThis.result) {`,
` var globalThisObjId = globalThis.result.objectId;`,
` var executionContextId = parseInt(globalThisObjId.split('.')[1], 10);`,
` worker._createExecutionContext(new CRExecutionContext(session, { id: executionContextId }));`, //NOTE: , this._id
`}`,