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

Why is it that vanilla HTML/JS (including React) opts for camelCase in its styling conventions, while CSS does not follow the same pattern

Each type of technology for styling has its own set of conventions when it comes to naming properties, with camelCase and hyphenated-style being the two main options. When applying styles directly to an HTML DOM Node using JavaScript, the syntax would be ...

What is the reason for having two plugin declarations within the galleriffic.js file?

I am currently working on enhancing the functionality of galleriffic.js by implementing a feature that will update a <div> element with text content as images are being changed. However, I am facing some challenges understanding the code. What perpl ...

implementing a feature to save and showcase a list of preferred names using jquery/ajax without the

On my website, individuals have the ability to search for any name from around the globe. Users can add specific names to their favorites list, which they can view on a separate page containing all of the names added during their current session. I would ...

AngularJS dropdown not reflecting changes when using ng-selected

While working with AngularJS, I have encountered an issue where the first child of the select element remains empty despite my efforts to populate it. Below is the HTML code snippet: <select id="connectTV" aria-label="How many Dish TVs" ng-model="conn ...

Blocked the loading of scripts due to non-compliance with the Content Security Policy directive

Encountering an error with externally loaded scripts: Refusing to load the script 'https://code.jquery.com/jquery-3.4.1.slim.min.js' due to violating the Content Security Policy directive: "script-src 'self' https://ajax.googlea ...

Angular appends "string:" in front of value when using ng-options

In my HTML, I have a ng-options list set up with a select element like this: <select required="required" ng-model="vm.selectedOption" ng-options="item.name as item.label for item in vm.options"> <option value="">Select an opti ...

Switching images with the hover effect using jQuery

I am attempting to dynamically change a down arrow image with jQuery on hover. I have explored using CSS background-image solutions, but my current setup already has a background in place. While I have come across similar questions before, I haven't ...

Adjusting Classes in JavaScript with jQuery

I need to create a feature that changes the state of a button from active to inactive based on user input, using Bootstrap. Ultimately, I am working towards finding an intuitive way to validate form input so that the submit button can be pressed for PHP pr ...

Receiving CORS response from the server for just one of the two API calls

Description of the issue: I am facing a peculiar problem where I am encountering different responses while making two calls to the same API. One call is successful, but the other returns a 504 error. Access to XMLHttpRequest at '' from orig ...

Managing consecutive synchronous side effects that are dependent on each other using React hooks

I am currently in the process of transitioning my application from using Redux to the new context and hooks, but I am facing challenges when it comes to handling a series of synchronous side-effects that rely on the response of the previous one. In my exi ...

Overcoming Challenges with Ajax Success in Bootstrap DataTable Modal

Recently, I created a webpage featuring a top fixed navbar and a CRUD datatable with pagination supported by buttons that trigger modals. However, I'm encountering an issue where upon clicking the delete button in the modal to remove a record, the mod ...

Avoid automatic scrolling when moving between tabs with varying lengths in Bootstrap Tabs

I am working with a series of Bootstrap tabs that contain content of various lengths: <ul class="nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item" role="presentation"> <button class="nav-link active" id="home-tab" data ...

Ways to delete a property from an element that was originally included with jquery

On my jsp page, I am implementing a jQuery autocomplete feature for a text field with the id "mytextfield". jQuery(function(){ $("#mytextfield").autocomplete("popuppages/listall.jsp"); }); Sometimes, based on user input and pr ...

The automated test locator in Angular using Protractor is failing to function

I am facing a challenge with my angular web application as there are some elements that are difficult to interact with. One specific element is a checkbox that needs to be checked during testing: ` <div class="row form-group approval_label"> < ...

Filtering data in Laravel can be efficiently achieved by utilizing Laravel's ORM hasmany feature in conjunction with Vue

Hey there, I'm currently working with Laravel ORM and Vue 2. I've encountered some issues with analyzing Json data. Here's my Laravel ORM code: $banner = Banner::with('banner_img')->get(); return response()->json($banner); ...

Validating group radio buttons that have been checked

I possess: <div class="group"> <input type="radio" name="myradio" value="1">a <input type="radio" name="myradio" value="2">b </div> <div class="group"> <input type="radio" name="two" value="3">a <input ty ...

Error encountered with Jest: SyntaxError - React Navigation - Unexpected export token found in [node_modules eact-navigationsrc eact-navigation.js:1]

Error Encountered with Jest:- The main issue arises from react navigation. There is an error occurring in jest related to the react-navigation node_modules folder. Error at: node_modules\react-navigation\src\react-navigation.js:1 Error Det ...

IE11 experiences frequent crashes when running a web application utilizing the Kendo framework and JavaScript

I am experiencing difficulties with my ASP.NET MVC application that utilizes Kendo UI and jQuery. Specifically, when using Internet Explorer 11, the browser crashes after a short period of usage. The crash does not seem to be linked to any specific areas o ...

Can you explain the significance of this HTML code?

While examining some source code, I came across the following: <div class="classname {height: 300px; width: 200px}"></div> I am aware that element styling can be done using the style="" attribute. Could you explain what this code snippet sig ...

Exploring the capabilities of SVG and audio integration in web browsers

I am curious if it's possible to incorporate audio into an SVG file in a web browser. I came across this thread here, but unfortunately, I can't leave a comment =/ I tried implementing the code from this website, but it doesn't seem to work ...