javascript validate css

javascript validate css

本文关键字:css validate javascript      更新时间:2023-09-26

我允许用户输入css。

在客户端验证css的一种轻松高效的方法是什么?

我正在寻找一个javascript解决方案。我不想把css发送到某个远程服务器或其他什么地方。

上下文:允许用户css

谢谢。

编辑:NVM关于这个问题。我开始使用服务器端验证器:https://github.com/chriso/node-validator

我认为这比@jcubic答案稍微安全一些,不会导致样式应用于当前文档:

function css_sanitize(css) {
    const iframe = document.createElement("iframe");
    iframe.style.display = "none";
    iframe.style.width = "10px"; //make small in case display:none fails
    iframe.style.height = "10px";
    document.body.appendChild(iframe);
    const style = iframe.contentDocument.createElement('style');
    style.innerHTML = css;
    iframe.contentDocument.head.appendChild(style);
    const sheet = style.sheet,
        result = Array.from(style.sheet.cssRules).map(rule => rule.cssText || '').join(''n');
    iframe.remove();
    return result;
}

您可以在应用程序中使用CSSLint引擎。其来源可在https://github.com/stubbornella/csslint

我需要一种方法来防止将html(导致XSS)代码注入到我的CSS编辑器中。我想出了这个(使用Native Browser DOM):

function css_sanitize(css) {
   var style = document.createElement('style');
   style.innerHTML = css;
   document.head.appendChild(style);
   var sheet = style.sheet;
   var result = Array.from(style.sheet.cssRules).map(rule => rule.cssText || '').join(''n');
   document.head.removeChild(style);
   return result;
}

基于stringify-css样式表(实际上几乎没有代码),拆分为两个NPM包的库的代码更少。

以下是演示:

function css_sanitize(css) {
   var style = document.createElement('style');
   style.innerHTML = css;
   document.head.appendChild(style);
   var sheet = style.sheet;
   var result = Array.from(style.sheet.cssRules).map(rule => (rule.cssText || '')).join(''n');
   document.head.removeChild(style);
   return result;
}
var output = css_sanitize(`:root {
    --color: red;
    --options: {"enabled": false}; /* some JSON in CSS */
}
</style>
<script>alert('x')</` + `script>
<style>`);
console.log(output);

在我的案例中,代码被注入到<style>{{CSS}}</style>中,因此当不受保护时,用户可以关闭样式注入脚本并打开样式。

function getDefinedCss(s){
    if(!document.styleSheets) return '';
    if(typeof s== 'string') s= RegExp('''b'+s+'''b','i'); // IE capitalizes html selectors 
    var A, S, DS= document.styleSheets, n= DS.length, SA= [];
    while(n){
        S= DS[--n];
        A= (S.rules)? S.rules: S.cssRules;
        for(var i= 0, L= A.length; i<L; i++){
                tem= A[i].selectorText? [A[i].selectorText, A[i].style.cssText]: [A[i]+''];
                if(s.test(tem[0])) SA[SA.length]= tem;
        }
    }
    return SA.join(''n'n');
}
// Then you check the class if exists by calling getDefinedCss('myclassname')