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 | package Torello.Browser;
import static Torello.Java.C.BRED;
import static Torello.Java.C.BCYAN;
import static Torello.Java.C.RESET;
import Torello.Browser.BrowserAPI.Network;
import Torello.Browser.BrowserAPI.Page;
import Torello.Browser.BrowserAPI.Target;
import Torello.Java.StrIndent;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* Demonstrates several CDP browser features without using JavaScript evaluation.
* <EMBED CLASS='external-html' DATA-FILE-ID=EX03_EXAMPLE>
*/
public class Example03
{
private Example03() { }
/** The URL used for demonstrating Network, Page, Screenshot, PDF and Cookie commands. */
protected static final String chineseURL =
"https://zh.wikipedia.org/wiki/%E4%BA%BA%E5%B7%A5%E6%99%BA%E8%83%BD";
/** The files generated by this example. */
protected static final String screenshotFile = "Example03-Screenshot.png";
protected static final String pdfFile = "Example03-Page.pdf";
private static ConnRecord connRec = new ConnRecord();
static
{
connRec.setEventHandler(Example03::eventHandler);
connRec.setRawTextReceiver(System.out);
connRec.setErrTextReceiver(System.out);
}
// ********************************************************************************************
// ********************************************************************************************
// Printing Helpers
// ********************************************************************************************
// ********************************************************************************************
/** Network URLs collected by the page-level handler. */
protected static final List<String> networkURLs = new ArrayList<>();
/** Page-level handler; this is where Network events become useful. */
static void eventHandler(BrowserEvent<?> be)
{
if (be instanceof Network.requestWillBeSent)
{
final Network.requestWillBeSent r = (Network.requestWillBeSent) be;
networkURLs.add(r.request.url);
System.out.println(
'\n' + BCYAN + "Example03.java: " + RESET +
BRED + "Network.requestWillBeSent" + RESET + '\n' +
" " + r.request.method + " " + r.request.url
);
}
else if (be instanceof Network.responseReceived)
{
final Network.responseReceived r = (Network.responseReceived) be;
System.out.println(
'\n' + BCYAN + "Example03.java: " + RESET +
BRED + "Network.responseReceived" + RESET + '\n' +
" " + r.response.status + " " + r.response.mimeType + '\n' +
" " + r.response.url
);
}
else if (be instanceof Network.loadingFinished)
{
final Network.loadingFinished r = (Network.loadingFinished) be;
System.out.println(
'\n' + BCYAN + "Example03.java: " + RESET +
BRED + "Network.loadingFinished" + RESET + '\n' +
" requestId: " + r.requestId + '\n' +
" bytes: " + r.encodedDataLength
);
}
};
// ********************************************************************************************
// ********************************************************************************************
// MAIN METHOD
// ********************************************************************************************
// ********************************************************************************************
/** This class is intended to be invoked from the Command Line. */
public static void main(String[] argv) throws Exception
{
STEP_01_initializeBrowserAndPage();
try
{
STEP_02_enablePageAndNetwork(connRec.pws);
STEP_03_navigateAndCollectNetworkTraffic(connRec.pws);
STEP_04_captureScreenshot(connRec.pws);
STEP_05_printToPDF(connRec.pws);
STEP_06_printCookies(connRec.pws);
}
finally
{
connRec.bws.disconnect();
connRec.pws.disconnect();
}
}
// ********************************************************************************************
// ********************************************************************************************
// The Steps
// ********************************************************************************************
// ********************************************************************************************
/** Open Chrome, close old tabs, create a new tab, and return both WebSocket senders. */
protected static void STEP_01_initializeBrowserAndPage() throws Exception
{
Printing.notice("Initialize BrowserConn, PageConn and WebSocketSender");
final BrowserConn browserConn = BrowserConn.getBrowserConn(9222, false);
System.out.println(
'\n' + BCYAN + "Example03.java: " + RESET +
BRED + "Opened Browser Connection:\n" + RESET + browserConn.toString()
);
final WebSocketSender bws = browserConn.createSender(connRec);
final Target.TargetInfo[] allTabs = Target
.getTargets(null /* FilterEntry[] */)
.exec(bws)
.await();
for (int i = 0; i < allTabs.length; i++)
if ("page".equals(allTabs[i].type))
Target.closeTarget(allTabs[i].targetId).exec(bws).await();
final String targetID = Target
.createTarget()
.accept("url", "about:blank")
.build()
.exec(bws)
.await();
final PageConn pageConn = PageConn
.getAllPageConn(9222, false)
.filter((PageConn pc) -> pc.id.equals(targetID))
.findFirst()
.orElseThrow(() -> new RuntimeException("The Page-Connection was Not Found"));
System.out.println(
'\n' + BCYAN + "Example03.java: " + RESET +
BRED + "Opened Page Connection:\n" + RESET + pageConn.toString()
);
final WebSocketSender pws = pageConn.createSender(connRec);
Thread.sleep(1000);
connRec.bws = bws;
connRec.pws = pws;
}
/** Enables the two CDP domains used throughout this example. */
protected static void STEP_02_enablePageAndNetwork(final WebSocketSender pws) throws Exception
{
Printing.notice("Enable Page and Network Domains");
System.out.println('\n' + BCYAN + "Example03.java: " + RESET + "Page.enable()");
Page.enable(null /* enableFileChooserOpenedEvent */).exec(connRec.pws).await();
System.out.println('\n' + BCYAN + "Example03.java: " + RESET + "Network.enable()");
Network
.enable(
null, // maxTotalBufferSize
null, // maxResourceBufferSize
null, // maxPostDataSize,
null // reportDirectSocketTraffic
)
.exec(connRec.pws)
.await();
}
/** Navigate to the target page and allow Network events to arrive through the handler. */
protected static void STEP_03_navigateAndCollectNetworkTraffic(final WebSocketSender pws)
throws Exception
{
Printing.notice("Navigate and Collect Network Traffic");
System.out.println(
'\n' + BCYAN + "Example03.java: " + RESET +
"Navigating To: " + chineseURL
);
Page
.navigate()
.accept("url", chineseURL)
.build()
.exec(connRec.pws)
.await();
Thread.sleep(5000);
System.out.println(
'\n' + BCYAN + "Example03.java: " + RESET +
BRED + "Total Network Request URL's Collected: " + RESET +
networkURLs.size()
);
for (int i = 0; i < networkURLs.size(); i++)
System.out.println(" " + networkURLs.get(i));
}
/** Capture the rendered browser page as a PNG file. */
protected static void STEP_04_captureScreenshot(final WebSocketSender pws) throws Exception
{
Printing.notice("Capture a PNG Screenshot");
final String pngBase64 = Page
.captureScreenshot()
.accept("format", "png")
.accept("fromSurface", true)
.build()
.exec(connRec.pws)
.await();
Files.write(Paths.get(screenshotFile), Base64.getDecoder().decode(pngBase64));
System.out.println(
'\n' + BCYAN + "Example03.java: " + RESET +
BRED + "Wrote Screenshot File: " + RESET + screenshotFile
);
}
/** Print the rendered browser page to a PDF file. */
protected static void STEP_05_printToPDF(final WebSocketSender pws) throws Exception
{
Printing.notice("Print the Page to a PDF File");
final Page.printToPDF$$RET pdf = Page
.printToPDF()
.accept("printBackground", true)
.build()
.exec(connRec.pws)
.await();
Files.write(Paths.get(pdfFile), Base64.getDecoder().decode(pdf.data));
System.out.println(
'\n' + BCYAN + "Example03.java: " + RESET +
BRED + "Wrote PDF File: " + RESET + pdfFile
);
}
/** Print the cookies visible to Chrome for the current page. */
protected static void STEP_06_printCookies(final WebSocketSender pws) throws Exception
{
Printing.notice("Read Browser Cookies for the Current Page");
final Network.Cookie[] cookies = Network
.getCookies(null /* String[] urls */)
.exec(connRec.pws)
.await();
System.out.println(
'\n' + BCYAN + "Example03.java: " + RESET +
BRED + "Cookies Returned: " + RESET + cookies.length
);
for (int i = 0; i < cookies.length; i++)
System.out.println(StrIndent.indent(cookies[i].toString(), 4));
}
}
|