繁体   English   中英

如何使用 javascript 从 web 页面获取所有图像 url?

[英]How to get all image urls from a web page using javascript?

有几种方法可以使用 javascript 加载图像 src url,例如使用document.images或选择所有img标签并获取 src。

但是我不知道如何在 css 中使用图像 url。

例如,如果网页有以下 css 代码,它会加载bg.png ,但我无法使用我上面提到的方法得到 url 。

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

任何人都知道如何在 css 中使用所有这些 url?

像这样的东西:

  1. 循环所有样式表规则
  2. 从样式表中获取文档元素
  3. 找到背景图片

 var sSheetList = document.styleSheets; for (var sSheet = 0; sSheet < sSheetList.length; sSheet++) { var ruleList = document.styleSheets[sSheet].cssRules; for (var rule = 0; rule < ruleList.length; rule ++) { if (rule.style.cssText.match(/background/)) { var selectorText = ruleList[rule].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. } } } }

资源时序 API收集关于出站请求的数据,应该保留在 CSS 和内联 styles 中收集图像的能力。

尚未对此进行测试,但类似的东西应该可以帮助您入门:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM