Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

html - How to get all image urls from a web page using javascript?

There are couple of ways to load image src urls using javascript, like using document.images or by selecting all img tags and get srcs.

However I can't figure out a way to image urls used within css.

For example, if the webpage has following css code, it loads bg.png, but I can't get that url using methods I mentioned above.

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

Anyone has an idea how to get all these urls used within css?

question from:https://stackoverflow.com/questions/65836625/how-to-get-all-image-urls-from-a-web-page-using-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The Resource Timing API collects data on outbound requests, should leave capacity to collect images in both CSS and inline styles performantly.

Haven't tested this, but something akin to this should help you get started:

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]);
                  }
                
               }
            });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...