【发布时间】:2017-12-05 22:04:51
【问题描述】:
上下文
我正在创建一个小型 jQuery 脚本:通过单击一个单词,用户可以擦除它并重写他想要的内容。
原始世界位于<span>。单击时,<span> 将替换为<input>。
没有<form>,没有提交按钮,只有这个<input>。
我的问题
当按下enter 键验证<input> 时,我的其余代码运行良好,除了javascript 注入:
<input type="text" value="<script>alert('Evil Script')</script>">
我的问题
在按下enter 键时,防止我的<input> 执行这个邪恶脚本的最佳方法是什么?
请原谅我天真的问题,并感谢您的建议。
我的代码错误
jQuery(document).ready(function($) {
initNom();
function initNom() {
var nomPerso = $('#nomPerso');
var cheminNom = localStorage.getItem('userName');
montrerNom();
nomPerso.on('click', function() {
$(this).replaceWith(
$('<input id="nomPerso" type="text" value="" placeholder="' + nomPerso.text() + '">')
);
$("#nomPerso")
.focus()
.on('keypress', function (e) {
if(e.which === 13) {
e.preventDefault();
//Disable textbox to prevent multiple submit
$(this).attr("disabled", "disabled");
sauverNom();
montrerNom();
$(this).replaceWith($('<span id="nomPerso">' + localStorage.getItem('userName') + '</span>'));
$(this).removeAttr("disabled");
initNom();
}
});
});
function sauverNom() {
var nom = $('#nomPerso').val();
if (typeof(Storage) !== "undefined" && nom) {
localStorage.setItem('userName', nom);
}
}
function montrerNom() {
if (!cheminNom) {
nomPerso.text('{Inserer_nom}');
} else {
nomPerso.text(cheminNom);
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="nomPerso"><script>alert('Evil Script')</script></div>
也在 CodePen 上:https://codepen.io/LaBriqueHurlante/pen/mwxjRL
【问题讨论】:
-
您需要展示您的代码,当他们看不到您当前拥有的内容时,没有人可以告诉您要更改什么。创建一个重现行为的minimal reproducible example。
-
无论您选择哪种方法,我都建议在服务器端设置另一层保护,以防某些恶意用户确实设法插入了一些脚本。尽你所能在客户端改进用户体验,但如果你有安全方面的考虑,你还应该清理服务器上的数据。
-
@Tomalak :对不起,我不想让这篇文章超载。我编辑了它,它有一个 codepen 的链接。
-
不用担心,将代码发布到编程网站不会超载,这与往常一样。我还在这里包含了代码。仅将代码放在外部站点上会使您的问题取决于链接,这没有用。对于未来,大多数 JS/HTML 场景都将嵌入到 SO 上的问题中,所有工具都在那里。
-
话虽如此,看看 contentediable:它更接近你想要的。
标签: javascript jquery input code-injection