【问题标题】:How to deal with different kinds of encoding in the javascript如何在 javascript 中处理不同类型的编码
【发布时间】:2010-09-08 09:58:15
【问题描述】:

我认识到,基于我要使用某些参数的上下文,至少有 4 种编码是避免执行损坏代码所必需的:

  1. 构造 javascript 代码时的 Javascript 编码,例如

    var a = "what's up ?"
    var b = "alert('" + a + "');"
    eval(b); // or anything else that executes b as code
    
  2. 使用字符串作为参数进入 url 时的 URL 编码,例如

    var a = "Bonnie & Clyde";
    var b = "mypage.html?par=" + a;
    window.location.href = b; // or anything else that tries to use b as URL
    
  3. 使用字符串作为某些元素的 HTML 源时的 HTML 编码,例如

    var a = "<script>alert('hi');</script>";
    b.innerHTML = a; // or anything else that interprets a directly
    
  4. 使用字符串作为属性值时的 HTML 属性编码,例如

    var a = 'alert("hello")';
    var b = '<img onclick="' + a + '" />'; // or anything else that uses a as a (part of) a tag's attribute
    

虽然在 ASP.NET 代码隐藏中,我知道在所有 4 种情况下对字符串进行编码的方法(例如使用 DataContractJsonSerializerHttpUtility.UrlEncodeHttpUtility.HtmlEncodeHttpUtility.HtmlAttributeEncode),这将非常有趣知道在这 4 种情况下我是否可以直接从 javascript 中使用一些实用程序来编码/解码字符串。

【问题讨论】:

  • 在情况 3 中,您是否试图避免 JavaScript 完全被执行?
  • 没错,在这种情况下我希望代码显示在页面上

标签: c# javascript asp.net html encoding


【解决方案1】:

情况2可以使用encodeURIComponent()处理,如danp suggested

案例 3 won't execute the script in most browsers。如果您希望文档的输出为&lt;script&gt;...&lt;/script&gt;,则应改为编辑元素的文本内容:

var a = "<script>alert('hi');</script>";
if ("textContent" in b)
    b.textContent = a; // W3C DOM
else
    b.innerText = a; // Internet Explorer <=8

案例 1 和 4 并不是真正的编码问题,它们是卫生问题。对传递给这些函数的字符串进行编码可能会导致语法错误,或者只是导致未分配给任何内容的字符串值。清理通常涉及寻找某些模式并允许或禁止该操作 - 拥有白名单比黑名单更安全(这听起来很糟糕!)。

Internet Explorer 8 有一个有趣的函数window.toStaticHTML(),它可以从 HTML 字符串中删除任何脚本内容。在插入 DOM 之前清理 HTML 非常有用。不幸的是,它是专有的,因此您在其他浏览器中找不到此功能。

【讨论】:

  • Re case 3 我相信 OP 的目标不是避免 JavaScript 执行,而是简单地对 html 进行编码(请参阅他对问题的评论)。
【解决方案2】:

您可以将 javascript 函数 escape(..) 用于其中一些目的。

e:居然忘了!抱歉,这是一个已弃用的功能 - encodeURI()decodeURI() 等是前进的方向!详情here.

escape 和 unescape 函数不 适用于非 ASCII 字符 并已被弃用。在 JavaScript 1.5 及更高版本,使用 编码URI,解码URI, 编码URIComponent,和 decodeURIComponent。

escape 和 unescape 函数让 你编码和解码字符串。这 转义函数返回 参数的十六进制编码 ISO 拉丁字符集。这 unescape 函数返回 ASCII 指定十六进制的字符串 编码值.编码值。

【讨论】:

  • 实际上,我相信 encodeURIComponent() 将完全涵盖案例 2.. 只剩下 3 个案例 :)
猜你喜欢
  • 1970-01-01
  • 2014-06-10
  • 1970-01-01
  • 2012-05-11
  • 1970-01-01
  • 1970-01-01
  • 2021-01-09
  • 2010-10-07
  • 1970-01-01
相关资源
最近更新 更多