Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

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.

Download a PDF file in Playwright instead of opening it in a new tab when clicking on its link

+1
−0

My organisation uses Moodle as their online e-learning system on which teachers share resources, and oftentimes numerous documents that we need to view/download are posted there. The default way of attaching documents (which is what everyone ends up using) requires the recipient to ctrl-click on the link, move to the tab just opened and ctrl+S for every PDF shared, which isn't exactly a 'git clone-experience'.

To get over this I tried using Playwright, famous for being able to automatically perform practically any useful action a human would, but everything I've tried has always caused a download promise to hang after the PDF opened in a new tab.

History

1 comment thread

I appreciate the self-answer, but this question isn't easily answerable by any other users. In your q... (1 comment)

2 answers

+1
−0

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 { 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 and Ecosia 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 });!

History

0 comment threads

+1
−0

This is as much as I was able to shorten it (it downloads all the visible links with \nTitle in their text):

import { chromium } from 'playwright';
(async () => {
  const browser = await chromium.launch();
  const context = await browser.newContext({ storageState: 'loggedInState.json'});
  const page = await context.newPage();
  await page.goto(mylink);
  const visibleLinksLocator = page.locator('a:visible');
  const linkTexts: string[] = await visibleLinksLocator.allInnerTexts();
  const filteredTexts = linkTexts.filter(linkText => linkText.includes("\nFile"));
  for (const text of filteredTexts) {
    const downloadPromise = page.waitForEvent('download');
    await page.getByText(text).click();
    const download = await downloadPromise;
    const fileName = download.suggestedFilename();
    await download.saveAs(`./downloads/${fileName}`);
  }
  await browser.close();
})();
History

0 comment threads

Sign up to answer this question »