简体   繁体   English

从 CSS 文件中提取所有 URL 链接

[英]Extract all URL links from CSS file

I have a asset file with CSS and that contains properties as: background-image: url(my-url.jpg) Im trying to extract all images from the url().我有一个带有 CSS 的资产文件,其中包含以下属性: background-image: url(my-url.jpg)我试图从 url() 中提取所有图像。 How can i achieve that in JS?我怎样才能在 JS 中实现它?

If the style sheet is loaded to the page, you can get theStyleSheetList , and pick your style sheet using document.styleSheets .如果样式表已加载到页面,您可以获取StyleSheetList ,并使用document.styleSheets选择样式表。 After selecting the style sheet, iterate it's rules with Array#reduce , extract the backgroundImage url using a regular expression, and if the result is not null (we have a url), push it into the urls array:选择样式表后,使用Array#reduce迭代它的规则,使用正则表达式提取 backgroundImage url,如果结果不为null (我们有一个 url),则将其推送到urls数组中:

You can can get relevant s你可以得到相关的s

 const result = [...document.styleSheets[0].rules] .reduce((urls, { style }) => { var url = style.backgroundImage.match(/url\\(\\"(.+)\\"\\)/); url && urls.push(url[1]); return urls; }, []); console.log(result);
 .bg { width: 100px; height: 100px; } .a { background: url(http://lorempixel.com/200/200); } .b { background: url(http://lorempixel.com/100/100); }
 <div class="bg a"></div> <br /> <div class="bg b"></div>

您可以使用.match().map().replace()

let res = CSSText.match(/url\(.+(?=\))/g).map(url => url.replace(/url\(/, ""));

I've extended @guest271314's answer with jQuery ajax.我已经用 jQuery ajax 扩展了 @guest271314 的答案。 You may use it.你可以使用它。

$(document).ready(function() {
    $.get("main.css", function(cssContent){
        let res = cssContent.match(/url\(.+(?=\))/g).map(url => url.replace(/url\(/, ""));
        alert( res );       
    }); 
});

I just wrote an updated version of this that iterates of all stylesheets on the page:我刚刚写了一个更新版本,它迭代页面上的所有样式表:

let css_urls = [...document.styleSheets]
  .filter(sheet => {
    try { return sheet.cssRules }
    catch {}
  })
  .flatMap(sheet => Array.from(sheet.cssRules))
  .filter(rule => rule.style)
  .filter(rule => rule.style.backgroundImage !== '')
  .filter(rule => rule.style.backgroundImage !== 'initial')
  .filter(rule => rule.style.backgroundImage.includes("url"))
  .reduce((urls, {style}) => {
    urls.push(style.backgroundImage);
    return urls;
  }, []);
  
console.log(css_urls);

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

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