To automate the process of spawning another page, retrieving its WebSocket URL, and performing actions such as navigating and taking a screenshot saved as a PDF, you can combine several steps. This involves listing the open targets, selecting a new target, connecting to its WebSocket URL, and performing the desired actions.
Step-by-Step Implementation
-
Start Firefox with Remote Debugging
Start Firefox with remote debugging enabled:
firefox --remote-debugging-port=9222
-
JavaScript Code to List Targets, Connect, Navigate, and Save PDF
Save the following script in a JavaScript file, e.g., multiPagePDF.js:
const WebSocket = require('ws');
const fs = require('fs');
const axios = require('axios');
const mainWsUrl = 'ws://localhost:9222/devtools/browser/...'; // Replace with the initial WebSocket URL
async function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function getNewTargetWsUrl() {
const targetsUrl = 'http://localhost:9222/json';
const response = await axios.get(targetsUrl);
const targets = response.data;
if (targets.length > 0) {
const newTarget = targets.find(target => target.type === 'page' && target.url === 'about:blank');
if (newTarget) {
return newTarget.webSocketDebuggerUrl;
} else {
console.log('No new target available.');
return null;
}
} else {
console.log('No targets found.');
return null;
}
}
async function saveAsPDF(urlToNavigate, outputPath, wsUrl) {
const ws = new WebSocket(wsUrl);
ws.on('open', async function open() {
// Navigate to the URL
const navigateMessage = JSON.stringify({
id: 1,
method: 'Page.navigate',
params: {
url: urlToNavigate
}
});
ws.send(navigateMessage);
// Wait for the page to load
await sleep(2000);
// Generate the PDF
const pdfMessage = JSON.stringify({
id: 2,
method: 'Page.printToPDF'
});
ws.send(pdfMessage);
});
ws.on('message', function incoming(data) {
const response = JSON.parse(data);
// Check for PDF response and save it to file
if (response.id === 2 && response.result && response.result.data) {
const pdfContent = response.result.data;
fs.writeFileSync(outputPath, pdfContent, 'base64');
console.log(`PDF saved to ${outputPath}`);
// Close the WebSocket connection
ws.close();
}
});
ws.on('error', function error(err) {
console.error('WebSocket error:', err);
});
ws.on('close', function close() {
console.log('WebSocket connection closed');
});
}
(async () => {
const newTabUrl = 'about:blank';
// Open a new tab
const ws = new WebSocket(mainWsUrl);
ws.on('open', async function open() {
const createTargetMessage = JSON.stringify({
id: 1,
method: 'Target.createTarget',
params: {
url: newTabUrl
}
});
ws.send(createTargetMessage);
});
ws.on('message', async function incoming(data) {
const response = JSON.parse(data);
if (response.id === 1 && response.result) {
// Wait a moment to ensure the new target is listed
await sleep(1000);
const newWsUrl = await getNewTargetWsUrl();
if (newWsUrl) {
const fileUrl = 'file:///path/to/your/file.txt'; // Replace with your file URL
const outputPath = 'screenshot.pdf'; // Replace with your desired output file path
await saveAsPDF(fileUrl, outputPath, newWsUrl);
}
}
ws.close();
});
ws.on('error', function error(err) {
console.error('WebSocket error:', err);
});
ws.on('close', function close() {
console.log('Main WebSocket connection closed');
});
})();
Explanation:
-
Main WebSocket URL:
- The
mainWsUrl is the WebSocket URL to the main DevTools instance. Replace 'ws://localhost:9222/devtools/browser/...' with the actual URL.
-
List Targets:
- The
getNewTargetWsUrl function fetches the list of targets by making an HTTP request to http://localhost:9222/json and returns the WebSocket URL for the new target.
-
Saving PDF:
- The
saveAsPDF function connects to the new target's WebSocket URL, navigates to the desired URL (fileUrl), and saves the page as a PDF (outputPath).
-
Open New Tab:
- The script first opens a new tab using
Target.createTarget with the URL 'about:blank'. It then waits briefly before listing the targets and finding the WebSocket URL for the new tab.
-
Navigating and Saving to PDF:
- After obtaining the WebSocket URL for the new tab, the script navigates to the specified file URL and saves it as a PDF, leveraging the
Page.printToPDF method.
Running the Script:
To run this JavaScript file, save it as multiPagePDF.js and run it using Node.js:
node multiPagePDF.js
By following this approach, you can automate the process of opening new tabs, navigating to URLs, and capturing screenshots saved as PDF files across different pages using the Chrome DevTools Protocol in Firefox. Adjust the script to suit your specific needs and don't forget to handle any necessary file permissions and security settings.