简体   繁体   English

有没有办法阻止JavaScript在我的网站上运行?

[英]Is there a way to keep JavaScript from running on my website?

My goal here is to stop any attempts at malicious JavaScript code insertion by users who can post content to my website. 我的目标是阻止可以向我的网站发布内容的用户插入恶意JavaScript代码的任何尝试。 Assuming my site has no use for JavaScript, is there some tag I can put at the top of each page or some other way to accomplish no possibility of JS running on my page? 假设我的网站没有使用JavaScript,是否有一些标记我可以放在每个页面的顶部或其他一些方式来实现JS在我的页面上运行的可能性? (a tiny bit of JS at the beginning of the page would be OK as long as it would make sure no more could execute) Thanks a bunch. (在页面开头的一小部分JS就可以了,只要它能确保不再执行)感谢一堆。

Yes, there is! 就在这里!

Most modern web browsers support the Content-Security-Policy header, which will allow you to declare in a HTTP header where your site will load certain types of content from, including Javascript code. 大多数现代Web浏览器都支持Content-Security-Policy标头,这将允许您在HTTP标头中声明您的网站将加载某些类型的内容,包括Javascript代码。 It is perfectly feasible to declare that your site will not load any Javascript code, nor declare any inline, and this will effectively disable Javascript on your site. 声明您的网站不会加载任何Javascript代码,也不会声明任何内联,这是完全可行的,这将有效地禁用您网站上的Javascript。

A simple policy that disables all Javascript might be: 禁用所有Javascript的简单策略可能是:

Content-Security-Policy: script-src 'none'

Keep in mind, however, that not all browsers implement Content-Security-Policy . 但请记住, 并非所有浏览器都实现了Content-Security-Policy You will still need to perform appropriate data sanitization to protect browsers which do not support CSP. 您仍需要执行适当的数据清理以保护不支持CSP的浏览器。

The type of attack you're trying to prevent is called cross-site scripting . 您尝试阻止的攻击类型称为跨站点脚本 so that's where you'll want to start for learning how to prevent it. 所以这就是你想要开始学习如何防止它的地方。

The simplest thing to do is to escape special characters in user input so that users can't post HTML tags such as <script> . 最简单的方法是转义用户输入中的特殊字符,以便用户无法发布HTML标记,例如<script> That'll work if users shouldn't be able to post HTML at all. 如果用户根本不能发布HTML,那将会有效。 If you need to allow some kinds of HTML but not scripts, then you should look into more sophisticated HTML-sanitization techniques. 如果您需要允许某些类型的HTML而不是脚本,那么您应该研究更复杂的HTML清理技术。

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

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