Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Post History
Since this is a Q&A site and it took me hours to figure out this small detail actually works, here is my working code in the hope this saves future users a lot of fruitless searching: const { ...
#1: Initial revision
Since this is a [Q&A site](https://meta.codidact.com/posts/290638/290640?sort=score) and it took me hours to figure out this small detail actually works, here is my working code in the hope this saves future users a lot of fruitless searching:
```js
const { chromium } = require('playwright'); // Use 'playwright' instead of '@playwright/test'
(async () => {
// Load the saved state
const state = require('./loggedInState.json'); // Directly require the JSON file
// Launch the browser with the saved state
const browser = await chromium.launch({ headless: true });
const context = await browser.newContext({ storageState: 'loggedInState.json', acceptDownloads: true });
const page = await context.newPage();
// Navigate to a protected page (you should already be logged in)
await page.goto('mylink'); // Replace with your target URL
console.log('Logged in successfully!');
await page.route('**/*.pdf', async route => {
const response = await route.fetch();
const headers = response.headers();
headers['content-disposition'] = 'attachment';
await route.fulfill({
response,
headers
});
});
const [download] = await Promise.all([
page.waitForEvent('download'),
page.getByText('pdflinkname').last().click()
]);
await download.saveAs('./downloads/document.pdf');
await browser.close();
})();
```
Most of it is a funky concoction of [Google AI Overviews](https://search.google/ways-to-search/ai-overviews/) and [Ecosia AI Chat](https://www.ecosia.org/ai-chat) which I'm sure any other answerer could do better, but I thought it was right to at least show something that worked to start off with (I ran this with `node <my-script-name>.js`). Unfortunately I can't share the exact page I was having issues with, as I connected to an intranet (hence `const state = require('./loggedInState.json');`), although the general principle should be the same, i.e: `const browser = await chromium.launch({ headless: true });` NOT `const browser = await chromium.launch({ headless: false });`!
