"How to Integrate External Stylesheets in Puppeteer for Enhanced Web Design

My puppeter Js code is not retrieving all external stylesheets, even though I need them for further processing. Here's what I have so far:

try {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    page.on('response', async response => { // There is no waiting here
        if(response.request().resourceType() === 'stylesheet') {
            resolve(response.text()); // Wait and resolve at this point
        }
    });

    await page.goto(url);
    await browser.close();
    // Do not resolve here
} catch (e) {
    return reject(e);
}

I'm encountering an issue where multiple external stylesheets are not being retrieved. How can I resolve this problem?

NOTE: I am using the resolve method because I require the stylesheets for subsequent processing and I need them to be returned.

Answer №1

To streamline the process, you can gather all stylesheets (or their associated Promises) into an array. Once the page has fully loaded and all Promises are resolved, you can then resolve the array.

Sample Code

try {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    const stylesheetPromises = [];

    page.on('response', async response => {
        if(response.request().resourceType() === 'stylesheet') {
            stylesheet.push(response.text());
        }
    });

    await page.goto(url);
    await browser.close();
    const stylesheets = await Promise.all(stylesheetPromises);
    resolve(stylesheets);
} catch (e) {
    return reject(e);
}

Within the context of this code snippet, the Promise is resolved with an array comprising strings that contain all the stylesheets. This is achieved by accumulating all response.text() Promises in an array, which are subsequently awaited using Promise.all. Subsequently, the results are returned.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learning to retrieve JSON data from an API using JavaScript

https://i.sstatic.net/OQZvD.pngGreetings! I am currently facing an issue while trying to retrieve JSON data from an API. Whenever I attempt to extract data from the API, everything works smoothly except for when I try to access the distance value, which re ...

It appears that the jQuery this() function is not functioning as expected

Despite all aspects of my simple form and validation working flawlessly, I am facing an issue where 'this' is referencing something unknown to me: $('#contact').validator().submit(function(e){ e.preventDefault(); $.ajax ...

Connects URLs to the displayed outcomes in jQuery Auto-suggest Interface

This particular code snippet has been modified from a tutorial on jQuery autocomplete <!doctype html> <html lang="en> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> ...

Extract specific data from JSON objects

I have a JSON string that I need to parse on the client side in order to extract data for three different column names (MAT_ETHNICITY, PAT_ETHNICITY, SEX). My goal is to populate drop down lists with the values. Should I handle this by making three separ ...

Tips for assigning a cookie as the id of a div?

I've been tasked with making the selected menu stand out when the page is refreshed. I'm thinking of using a cookie to achieve this. Here's the HTML code: <div class="menuBar"> <div class="menuHeader ui-corner-top"> ...

Trouble accessing data with AJAX

I am trying to retrieve content from a web page and display it on my own webpage using AJAX. However, I keep encountering an "Access denied" error before the specified page is fetched. It's important to note that the target page does not require any l ...

Implementing server authentication with Faye in Node.js

As a complete newbie to node.js and faye, I'm struggling with the basics and not sure what questions to ask. This is how my faye server setup looks like, running on Nodejitsu: var http = require('http'), faye = require('faye' ...

React component failing to update after receiving response from server for a specific room using socket.io-client with Python backend

I've developed a server backend in Python with Flask-SocketIO that includes a room feature for private conversations. When a user joins a room, the server triggers a function to inform the frontend where to direct messages to a specific user: socketio ...

Iterating through each loop and storing the values in an array

After researching various topics related to the issue, I found that the solutions provided are not working for me. It seems like there is a logic problem in my code. It's quite simple - I have two arrays (one containing three strings and the other con ...

Can the window opened by window.open in Javascript be closed?

My goal is to overload a website I am visiting in order to crash it by sending an excessive amount of requests to overwhelm the server it is hosted on. My current script is quite basic: while ( true ) { window.open(window.location.href); } This script co ...

Sending an AJAX request to a Controller Action using an Object as input

I am currently using an AJAX call to a Controller within an ASP.NET MVC solution. The code snippet for the AJAX call is as follows: $.ajax({ url: "ControllerClass/ControllerMethod?date=" + date, type: "POST", dataType: 'json&a ...

Step-by-step guide on interacting with a JavaScript menu: Click to open the menu and close it by moving

My menu JavaScript function now opens with a click and closes with a click. I want it to open with a click and close when the mouse leaves the button. $("#theme_select").click(function() { if (theme_list_open == true) { $(".center ul li ul").h ...

Unable to render HTML through Jquery ajax functionality

success: function(json) { for (var i = 0; i < json.length; i++) { var response = json[i]; $('#rv-container').html('<p>' + response.name + '</p>' + '<span>' + response ...

Compatibility issues between jQuery and AngularJS are causing problems

Currently, I am facing a compatibility issue between RequireJS and Angular in my setup. Everything functions without any problems when using jQuery version 1.7.2. However, I wanted to upgrade to jQuery 1.8.1 along with jQuery UI, but unfortunately, my Angu ...

The action 'addSection' is restricted to private access and can only be utilized internally by the class named 'File'

const versionList = Object.keys(releaseNote) for (const key of versionList) { // Skip a version if none of its release notes are chosen for cherry-picking. const shouldInclude = cherryPick[key].some(Boolean) if (!shouldInclude) { continue } // Include vers ...

Is there a way to stop the dropdown from automatically appearing in a DropDownList?

Seeking a solution to use a custom table as the dropdown portion for a DropDownList in my project. My goal is for users to see the custom table when they click on the DropDownList, rather than the default dropdown menu. I expected to be able to achieve th ...

Decoding various JSON arrays received through AJAX requests

After returning two objects as JSON through AJAX, I am facing an issue with accessing the values in these two lists. Previously, when I had only one list, I could parse it easily. data = serialize("json", vm_obj) data2 = serialize("json", user_networks_li ...

Adding a text field dynamically with angular2 can be achieved by using Angular's `

Hey everyone, I'm currently working on a project using angular2 and I've been attempting to dynamically add an input text field. It seems to be working fine but here's the code snippet: Typescript (TS): initArray() { return this._fb.gr ...

Using external VB script (IE automation) to invoke Java Script on a webpage

On a webpage, there is a functionality where a checkbox can be clicked to select all the checkboxes below it. This is accomplished by invoking a JavaScript function on click. However, when attempting to select that checkbox using VBScript with .getElement ...

What is the best way to highlight selected navigation links?

Recently, I implemented a fixed navigation bar with relevant links on a website. The navbar includes a jquery script for smooth scrolling when clicked. However, I am struggling to add a selected class to the clicked link. Despite trying various solutions f ...