Include onload to element without running it in Puppeteer

I am currently developing a web scraping tool using Puppeteer. Once the webpage is fully loaded, I need to update the HTML code and include an onload event for certain elements.

The issue is that in Puppeteer, the onload event is actually triggered automatically.

For example, the original element looks like this:

<link rel="stylesheet" href="style.css"/>

To modify the element using Puppeteer's page.evaluate method, I use the following code snippet:

elem.setAttribute('rel', 'preload');
elem.setAttribute('as', 'style');
elem.setAttribute('onload', "this.rel='stylesheet'");

Expected result:

<link rel="preload" as="style" href="style.css" onload="this.rel='stylesheet'" />

Actual result:

<link rel="stylesheet" as="style" href="style.css" onload="this.rel='stylesheet'"/>

Is there any way to bypass or prevent this automatic onload behavior in Puppeteer? Alternatively, could this task be accomplished more effectively using an HTML parsing library such as Cheerio?

Answer №1

Upon arrival to the page, make sure to immediately invoke page.setOfflineMode. By doing so, you will effectively prevent the loading of styles from preload and ultimately halt the onload event!

Example:

await page.goto(url, {
    waitUntil: 'networkidle2',
});

await page.setOfflineMode(true);

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

Is there a way to retrieve the HTML raw code using backticks for string interpolation in JavaScript?

I am working on a resume builder project where the HTML template file is stored in Firebase storage and retrieved using a URL. The template has been modified to include string interpolation, such as <h1>${name}</h1>. However, when I fetch the d ...

Troubleshooting a problem with selecting options in Jquery

Looking for assistance with a jquery script. I have a select dropdown that fetches a list of options via Ajax. When a user clicks on an option, if a certain variable equals 1, an HTML div is added. If the variable changes to another value, the HTML div dis ...

Creating a polyBezier or polyCurve with Canvas HTML: a step-by-step guide

Looking to connect several points with a curve rather than just a straight line. I attempted using the lineTo() and bezierCurveTo() methods to draw the points. Is there anyone who can assist me in solving this dilemma? Perhaps there is a different approac ...

Arrangement of images in an array

Here's the scenario I'm facing. https://i.stack.imgur.com/FbAfw.jpg So, I have an array of images that I want to use to create a gallery with a specific layout. I've tried using grid and playing around with :nth-child(even) and :nth-child( ...

Deleting all JSON files in a directory using NodeJs

Is there a way to delete only the json files within a directory (multiple levels) without specifying each file name individually? I thought fs-unlinkSync(path) might work, but I haven't found that solution yet. I attempted to use the following method ...

AntD Functional Component with Row Selection Feature

Is there a way to retrieve the key of a single element in the table instead of getting undefined? How can I extract the id? Check out this link for more information. const [select, setSelect] = useState({ selectedRowKeys: [], loading: false, }); ...

triggering ajax events before server response

I am facing an issue with ajax post data to my express server in nodejs. I have a callback function on the server side that responds to the client ajax after completing DB access. However, the ajax .fail is firing before my server callback function complet ...

Could the slow loading time of the React site be attributed to an overload of static assets?

As a ML professional diving into frontend development, I have recently incorporated various fixed assets such as images into the assets folder for React. However, I've noticed that my website is running slower than expected. Do you believe that these ...

I'm experiencing an issue when trying to align TextPath to the center in an SVG file - a certain character

When using the startOffset or text-anchor attributes, I noticed that some characters are missing. How can I fix this issue? Thank you. It appears that in this scenario, the characters `1234` are missing. <svg xmlns="http://www.w3.org/2000/svg" versi ...

An unforeseen issue occurred while trying to access an indexed element ID

I've recently started learning javascript and jquery, and encountered a problem while working on a script. The script is created by php code that reads lines from a file, processes them, and displays them using arrays. In addition, javascript validat ...

Complete Form Validation Issue Unresolved by Jquery Validation Plugin

I'm facing an issue with the jQuery validation plugin while attempting to validate a form. Strangely, it only works for one input field. Can anyone suggest a solution? <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.valid ...

We were caught off guard by the TypeScript error: an unexpected token showed up when we were expecting a constructor,

Trying to implement a function within a class in TypeScript. class Test { function add(x: number, y: number): number { return x + y; } } Encountering an error message stating: TypeScript Unexpected token, A constructor, method, access ...

Issue with a Jquery toggleClass function not working properly on hover

Hello everyone! I am a newbie in the community and relatively new to the world of web programming. I am encountering an issue that is really frustrating me. I attempted to use this code to add a class when hovering over the ul list element so that I can d ...

Invoking a module function within a callback function in Node.js

I created a module that logs data to a file using Coffeescript. Here's an example: require = patchRequire(global.require) fs = require('fs') exports.h = log: ()-> for s in arguments fs.appendFile "log.txt", "#{s}\n", ( ...

Having difficulty uploading an image to Facebook through the graph API

I have a requirement to upload a photo to Facebook using the Javascript SDK, but I am experiencing some difficulties: Firstly, FB.login(function (response) { if (response.authResponse) { va ...

Step-by-step guide to setting up a TypeScript project on Ubuntu 15 using the

As a newcomer to UBUNTU, I have recently ventured into learning AngularJS2. However, when attempting to install typescript using the command: NPM install -g typescript I encountered the following error message: view image description here ...

What is the best way to refine the results from an AJAX request in Datatables?

I have successfully configured a Datatables plugin, set up a new table, and populated it with content using an AJAX call: var table= $("#mytable").DataTable({ ajax: "list.json", columns: [ {"data": "name"}, {"data": "location"}, ...

What is the best method for establishing a connection between NodeJS and PostgreSQL?

I'm having trouble figuring out the correct way to connect a PostgreSQL pool in my NodeJS application. I am using Express with Router, and all of my handlers are located in different files. Many people recommend creating a separate file for the DB con ...

Encountering a missing value within an array

Within my default JSON file, I have the following structure: { "_name":"__tableframe__top", "_use-attribute-sets":"common.border__top", "__prefix":"xsl" } My goal is to add values by creating an array, but I am encountering an issue where my ...

The Promise.all() is being triggered before the completion of the resolve() promise

Recently, I've started working with node and I'm attempting to create a service that will interact with AWS to load multiple images and then provide the AWS keys back to the client. To achieve this, I am utilizing Promise.all to handle all of the ...