简体   繁体   English

使用JavaScript从HTML DOM树中剥离JavaScript

[英]Strip JavaScript from HTML DOM Tree with JavaScript

How can one possibly sanitize a HTML DOM Tree from all JavaScript occurrences, meaning: on(click|mouseover|etc) , href:javascript... , <script> and all other possible variants of (inline) JavaScript, while using JavaScript? 在使用JavaScript时,如何从所有出现的JavaScript中清除HTML DOM树,这意味着: on(click|mouseover|etc)href:javascript...<script>和(inline)JavaScript的所有其他可能的变体?

For example: I want users to upload their HTML file, copy the contents in the <body> tags and insert it into one of my pages. 例如:我希望用户上载HTML文件,将内容复制到<body>标记中,然后将其插入到我的页面之一中。 I don't want to allow JavaScript in their HTML files. 我不想在其HTML文件中使用JavaScript。 I could use <iframe sandbox> , but I wondered whether there is another way. 我可以使用<iframe sandbox> ,但是我想知道是否还有另一种方法。

The following uses the Element.attributes collection to remove inline on handlers and attributes containing the word, "javascript" – without affecting other DOM attributes. 下面使用Element.attributes集合删除处理程序和包含单词“ javascript”的属性的内联on而不会影响其他DOM属性。

 function disableInlineJS() { var obj = document.querySelectorAll('*'); for (var i = 0; i < obj.length; i++) { for (var j in obj[i].attributes) { var attr = obj[i].attributes[j]; if ((attr.name && attr.name.indexOf('on') === 0) || (attr.value && attr.value.toLowerCase().indexOf('javascript') > -1) ) { attr.value= ''; } } } } 
 <button onclick="disableInlineJS()">Disable inline JavaScript</button><hr> <div onmouseover="this.style.background= 'yellow';" ONmouseout="this.style.background= '';" style="font-size:25px; cursor: pointer;"> Hover me <br> <a href="javAsCriPT:alert('gotcha')" style="font-weight:bold">Click me!</a> <br> <a href="http://example.com">Example.com!</a> </div> <button onclick="alert('gotcha')">Me, me!</button> 

I don't think there's a way to remove script elements before they've had a chance to run. 我认为没有办法在script元素运行之前将其删除。

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

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