代码之家  ›  专栏  ›  技术社区  ›  emil

如何使用javascript从网页中获取所有图像url?

  •  1
  • emil  · 技术社区  · 5 年前

    有几种方法可以使用javascript加载图像src url,比如使用 document.images 或选择全部 img 标记并获取srcs。

    然而,我无法找到一种方法来对css中使用的url进行图像处理。

    例如,如果网页有以下css代码,它将加载 bg.png ,但我无法使用上面提到的方法获取该网址。

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

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

    1 回复  |  直到 5 年前
        1
  •  1
  •   Squiggs.    5 年前

    这个 Resource Timing API 收集出站请求的数据,应该能够高效地收集CSS和内联样式的图像。

    还没有测试过这个,但类似的东西应该能帮助你开始:

    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]);
                      }
                    
                   }
                });
    
        2
  •  1
  •   Squiggs.    5 年前

    像这样:

    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.
               }
               }
              
            }
        }