javascript validate css
javascript validate css
我允许用户输入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')
相关文章:
- CSS-如何定位内容数据标题
- 窗口大小html css
- 如果文本字段为空,则使用JavaScript应用CSS样式
- 动画.CSS重播
- 有没有一种方法可以防止img get请求使用css或js发生
- CSS表格:从列平移到整个表格宽度
- CKEditor-我在editor.css中的风格是't
- 单击更改图标并通过javascript添加一个css类
- 将CSS应用于printWindow.print();在Javascript中
- 使用CSS或js,使用动态选择器选择任意li的下一个元素
- CSS-若窗口太小,滚动条会出现在“表格”单元格上
- css(或jQuery)悬停时淡入淡出
- 为什么不'在JQuery中找到第二个css选择器的工作
- 为什么 .focus() 不起作用,而 .css(“color”,“red”) 在同一个选择器上起作用
- 如何使用css动画/javascript使具有背景图像的元素出现
- 获取HTML属性中CSS声明的值
- 当我更改Joomla时,它仍然从旧域加载CSS和Javascript
- jQuery validate-更改无效元素的css
- javascript validate css
- jQuery validate ".error" field CSS