What is the best way to extract all image URLs from a website using JavaScript?

There are various methods to retrieve image src urls using JavaScript, such as utilizing document.images or by targeting all img elements and fetching their src attributes.

However, I am currently unable to extract the image urls specified within CSS styles.

For instance, consider a scenario where the webpage contains the following CSS snippet that loads bg.png, but it's challenging for me to capture that URL with the aforementioned approaches.

.bg {
  background-image: url('bg.png');
}

Does anyone know a solution to independently fetch all these URLs utilized inside CSS?

Answer №1

The Resource Timing API is a powerful tool for collecting data on outbound requests, allowing you to efficiently gather information about images used in both CSS and inline styles.

While I have not personally tested the following code snippet, it can serve as a starting point for implementation:

if (!('performance' in window) || !('getEntriesByType' in window.performance) || !(window.performance.getEntriesByType('resource') instanceof Array)) {
    alert('unsupported');
} else {
    window.addEventListener('load', function() {
        var resources = window.performance.getEntriesByType('resource');
        for (var index in resources) {
            for (var properties in resources[index]) {
                console.log(properties);
                console.log(resources[index][properties]);
            }
        }
    });
}

Answer №2

Here are the steps to achieve this:

  1. Iterate through all stylesheet rules
  2. Retrieve the document element from the stylesheet
  3. Locate the background image
var styleSheetList = document.styleSheets;
    for (var styleSheetIndex= 0; styleSheetIndex < styleSheetList.length; styleSheetIndex++)
    {
        var ruleList = document.styleSheets[styleSheetIndex].cssRules;
        for (var ruleIndex = 0; ruleIndex < ruleList.length; ruleIndex ++)
        {
           if (rule.style.cssText.match(/background/)) {
           var selectorText = ruleList[ruleIndex].selectorText );
           var img = document.getElementsByClassName(selectorText);
           var style = img.currentStyle || window.getComputedStyle(img, false);
           if( style.backgroundImage ) {
               var bg = style.backgroundImage.slice(4, -1).replace(/"/g, "");
 //add to array here or whatever.
           }
           }
          
        }
    }

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

The function of the React index key appears to be malfunctioning within the map function

I've been encountering issues despite using the index key and also attempted utilizing a unique id from JSON data, but unfortunately haven't found a solution yet. ERROR Warning: Each child in a list should have a unique "key" prop. const fa ...

Is it possible to adjust the height of the dropdown menu in a mat-select component in Angular 7?

How can I adjust the height of a mat-select in Angular7 to display all items properly? Here is my component file: import { Component, ViewEncapsulation } from "@angular/core"; import { FormControl } from "@angular/forms"; /** @title Select with multiple ...

The presence of Null is detected during the HTML parsing process

I'm in the process of developing dynamic HTML pages using JSON data. Each time the application encounters a special identifier like #@, it gets replaced by a specific value. However, upon loading my page, I noticed that a null is being printed at the ...

creation of cascading drop-down lists

I have been struggling to create a dependent dropdown list using ajax and php, but unfortunately I am not getting the desired outcome. Below is my ajax code: <html> <head> <title>findperson</title> <script type="text/javascript ...

Issues with Image Loading in Azure WebMatrix

I am currently using WebMatrix to host my website, but I'm facing some issues with certain elements not loading correctly. Specifically, I have two pictures on my site that are linked to a directory on my local machine. I would like to know how I can ...

Real-time chat system using PHP for one-on-one inquiries with server-sent events (not a group chat)

I'm currently working on developing a live chat inquiry form for a website using HTML server-sent events. I'm utilizing this tutorial as a foundation Here is my plan based on the tutorial: On the client side, users are prompted to enter a use ...

Tips on showcasing a nested array in Next.js or converting it into an object

{ "count": 2, "rows": [ { "id": "5ab46e31-391c-46a7-8e45-db9ada07626d", "name": "admin", "email": "<a href="/cdn-cgi/l/email-p ...

Is there a way to implement word wrapping in li text without making any changes to its width

Is there a method to wrap the content inside li elements without modifying their width? As an illustration, consider the following structure - <ul> <li>Text Example</li> <li>Text Example</li> <li>Text Exampl ...

centered logo in a flexbox header

Having trouble with Flex for the first time. Despite reading and experimenting, I still can't figure it out. Any suggestions on how to accomplish this? Check out an example ...

Strange occurrences with the IMG tag

There seems to be an issue with my IMG element on the webpage. Even though I have set the height and width to 100%, there is some extra space at the end of the image. You can view the problem here: I have also included a screenshot from the developer too ...

Incorporating RFID reader functionality into a website

I am currently facing an issue with integrating an RFID card reader into a web page. After some research, it seems that the solution involves creating an ActiveX component and using JavaScript. My question is, how can we go about building an ActiveX compo ...

Exploring the depths of JSON using @attributes and @association in the realm of JavaScript and AngularJS

Currently, I am working on a project that involves utilizing an API for data retrieval, updates, and deletions. The API in question is the prestashop API. While I have managed to retrieve data and update certain items successfully, I encountered an issue. ...

How to dynamically set a computed background image in Vue 2

I have several divs that I want to style with backgrounds from values stored in an array. My attempt to set the background overlay for each one by creating a computed property has not been successful: computed: { backgroundImage(url) { let ...

Unable to trigger AJAX POST with jQuery click handler

Important Note: Personally, I have a preference for utilizing jQuery over the shorthand $; although it involves more typing, I find it to be more readable. I am working on a simple form that allows users to input their first and last names as well as an e ...

CSS creates captivating image hover transitions with span elements

<a href=""><img src=""><span>content</span></a> When I hover over the image, the content within the span appears using relative positioning with display set to none and absolute positioning in the span tag. My query is regard ...

Update your MySQL database with ease by leveraging the power of AJAX through a dropdown menu

Can you provide guidance on updating a MySQL database using a dropdown menu and Ajax without reloading the entire webpage? I am facing issues with implementing the code, even after referring to various tutorials. Below is a snippet of my PHP script within ...

Which Express.js template allows direct usage of raw HTML code?

I am in search of a template that utilizes pure HTML without any alterations to the language, similar to Jade but keeping the HTML as is. The reason behind this inquiry is: I prefer the simplicity and clarity of HTML I would like to be able to easily vi ...

dividing an HTML string into individual variables using JavaScript

How can a string be split in pure JavaScript (without using JQuery/dojo/etc) in the most efficient and straightforward way? For example: var tempString = '<span id="35287845" class="smallIcon" title="time clock" style="color:blue;font-size:14px;" ...

The functionalities of Google Maps are experiencing issues within AngularJS when utilizing the $route feature

Having Issues with Google Maps in AngularJS when using <ng-view></ng-view> Routing Configuration app.config(function($routeProvider, $locationProvider) { $locationProvider.html5Mode(true); $routeProvider .when('/', { t ...

Ways to modify the final sum exclusively for a single table

I am currently struggling to figure out how to calculate only the grand total of the first table using just one jQuery/JavaScript script. The code I am referencing is from: Below is the code snippet: <!DOCTYPE html> <html xmlns="http://www.w3 ...