在脚本标签中嵌入JSON对象 [英] Embedding JSON objects in script tags
问题描述
编辑:为了将来参考,我使用非xhtml内容类型定义<!html>
For future reference, I'm using non-xhtml content type definition <!html>
我正在使用Django创建一个网站,我试图在我的网页中嵌入任意的json数据,以供客户端JavaScript代码使用。
I'm creating a website using Django, and I'm trying to embed arbitrary json data in my pages to be used by client-side javascript code.
让我们说我的json对象是 {foo:< / script>}
。如果我直接嵌入,
Let's say my json object is {"foo": "</script>"}
. If I embed this directly,
<script type='text/javascript'>JSON={"foo": "</script>"};</script>
第一个关闭json对象。 (也会使得站点易受XSS影响,因为这个json对象将被动态生成)。
The first closes the json object. (also, it will make the site vulnerable to XSS, since this json object will be dynamically generated).
如果我使用django的HTML转义函数,结果输出是:
If I use django's HTML escape function, the resulting output is:
<script type='text/javascript'>JSON={"foo": "</script>"};</script>
,浏览器无法解释< script>
标签
我在这里的问题是,
- 哪些字符我想在这种情况下逃脱/不逃避?
- 在Python / django中有自动执行方式吗?
推荐答案
如果您使用XHTML,您将能够使用实体引用(& lt;
,& gt;
,& amp; amp; amp;< / code>)才能在
<脚本>
。您不会想使用<![CDATA [...]]>
部分,因为序列不能在CDATA部分中表达,您必须更改脚本以表达
]]>
。
If you are using XHTML, you would be able to use entity references (<
, >
, &
) to escape any string you want within <script>
. You would not want to use a <![CDATA[...]]>
section, because the sequence "]]>
" can't be expressed within a CDATA section, and you would have to change the script to express ]]>
.
但是你可能不使用XHTML。如果您使用常规HTML,则< script>
标签的行为有点像XML中的CDATA部分,除了它有更多的陷阱。它以< / script>
结尾。还有奥秘规则允许<! - document.write(< script> ...< / script>) - >
注释和< script>
开始标签必须同时存在以供< / script>
传递。 HTML5编辑器为未来浏览器采用的妥协是在 HTML 5标记化和 CDATA逃生
But you're probably not using XHTML. If you're using regular HTML, the <script>
tag acts somewhat like a CDATA section in XML, except that it has even more pitfalls. It ends with </script>
. There are also arcane rules to allow <!-- document.write("<script>...</script>") -->
(the comments and <script>
opening tag must both be present for </script>
to be passed through). The compromise that the HTML5 editors adopted for future browsers is described in HTML 5 tokenization and CDATA Escapes
我认为外卖是必须防止在您的JSON中发生< / script>
,为了安全起见,您还应该避免< script>
,<! -
和 - > / code>以防止失控的评论或脚本标签。我认为只需用
\\\<
和 - >替换
与<
- \>
I think the takeaway is that you must prevent </script>
from occurring in your JSON, and to be safe you should also avoid <script>
, <!--
, and -->
to prevent runaway comments or script tags. I think it's easiest just to replace <
with \u003c
and -->
with --\>
这篇关于在脚本标签中嵌入JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!