[英]How do I properly escape inline Javascript in a <script> tag?
I'm writing a server-side function for a framework that will let me inline a Javascript file. 我正在为一个框架编写一个服务器端函数,让我可以内联一个Javascript文件。 It takes the filename as input, and its output would be like this: 它将文件名作为输入,其输出如下:
<script>
/* contents of Javascript file */
</script>
How do I escape the contents of the Javascript file safely? 如何安全地转义Javascript文件的内容?
I am particularly worried if the file contains something like </script>
. 如果文件包含类似</script>
我特别担心。 If the input Javascript file has syntax errors, I still want it to escape correctly. 如果输入的Javascript文件有语法错误,我仍然希望它正确转义。 I also realise that XHTML expects some entities to be encoded, whereas HTML doesn't. 我也意识到XHTML期望一些实体被编码,而HTML则不然。
There are a lot of questions similar to this asking about how to escape string literals or JSON . 有很多类似的问题询问如何转义字符串文字或JSON 。 But I want something that can handle the general case, so that I can write a tool for the general case. 但我想要能够处理一般情况的东西,以便我可以为一般情况编写工具。
(I realise inlining potentially untrusted Javascript isn't the best idea, so no need to spend time discussing that.) (我意识到内联可能不受信任的Javascript不是最好的主意,所以不需要花时间讨论它。)
This is a work in progress, let me know if I've missed a corner case! 这是一项正在进行中的工作,请告诉我,如果我错过了一个角落案例!
The answer is different depending on whether you're using XHTML or HTML. 根据您使用的是XHTML还是HTML,答案会有所不同。
Content-Type: application/xhtml+xml
header 1.带有Content-Type: application/xhtml+xml
XHTML Content-Type: application/xhtml+xml
标头 In this case, you can simply XML escape any entities, turning this file: 在这种情况下,您可以简单地XML转义任何实体,转换此文件:
console.log("Example Javascript file");
console.log(1</script>2/);
console.log("That previous line prints false");
To this: 对此:
<script>
console.log("Example Javascript file");
console.log(1</script>2/);
console.log("That previous line prints false");
</script>
Note that if you're using XHTML with a different Content-Type
header, then different browsers may behave differently, and I haven't researched it, so I would recommend fixing the Content-Type
header. 请注意,如果您使用的XHTML具有不同的Content-Type
标头,那么不同的浏览器可能会有不同的行为,我还没有研究它,所以我建议修复Content-Type
标头。
Unfortunately, I know of no way to escape it properly in this case (without at least parsing the Javascript). 不幸的是,我知道在这种情况下没有办法正确地逃避它(至少解析Javascript)。 Replacing all instances of /
with \\/
would cause some Javascript to break, including the previous example. 替换/
with \\/
所有实例会导致某些Javascript中断,包括前面的示例。
The best that I can recommend is that you search for </script
case-insensitively and throw an exception if you find it. 我可以推荐的最好的是你搜索</script
不区分大小写,并在你找到它时抛出异常。 If you're only dealing with string literals or JSON, substitute all instances of /
with \\/
. 如果您只处理字符串文字或JSON,请替换/
with \\/
所有实例。
Some Javascript minifiers might deal with </script
in a safe manner perhaps, let me know if you find one. 一些Javascript minifiers可能会以安全的方式处理</script
,如果你找到一个,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.