[英]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.有几种方法可以使用 javascript 加载图像 src url,例如使用document.images
或选择所有img
标签并获取 src。
However I can't figure out a way to image urls used within css.但是我不知道如何在 css 中使用图像 url。
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.例如,如果网页有以下 css 代码,它会加载bg.png
,但我无法使用我上面提到的方法得到 url 。
.bg {
background-image: url('bg.png');
}
Anyone has an idea how to get all these urls used within css?任何人都知道如何在 css 中使用所有这些 url?
something like this:像这样的东西:
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. } } } }
The Resource Timing API collects data on outbound requests, should leave capacity to collect images in both CSS and inline styles performantly. 资源时序 API收集关于出站请求的数据,应该保留在 CSS 和内联 styles 中收集图像的能力。
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]);
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.