读取函数参数的eval()有多糟糕

时间:2016-05-08 18:26:49

标签: javascript jquery

我使用Hopscotch在我的网站上进行了导览。现在为此你必须创建一个JS对象,它将作为调用startTour()函数的参数,该函数将启动Tour。 在此示例中,通过单击a.hopscotch-start链接启动巡视。

HTML:

<a href="#" class="hopscotch-start" data-name="x">Start tour</a>

JS:

var x = {id: "tour1", steps: [{title: "the title",....}]};
$("a.hopscotch-start").click(function (e) {
  e.preventDefault();
  hopscotch.startTour(eval($(this).data('name'))); // -> startTour(x);
  return false;
}

这实际上有多糟糕?我知道eval是“慢”的,但它会让我灵活地只有一个通用的点击代码而不再费心了。如果有的话,实际的安全风险是多少?并且这会使代码显着变慢(关于代码只是读取要解析为变量的字符串的事实)。

感谢您的反馈 - 我们也欢迎任何其他解决方案而不是eval。

2 个答案:

答案 0 :(得分:1)

如果有任何方式修改了属性的值,您现在已经从服务器执行了任意JavaScript。

真正的问题是:为什么?

如果您使用对象作为查找,则不需要eval

var data = {
  x: {...},
  y: {...},
  ...
};
$("a.hopscotch-start").click(function (e) {
  e.preventDefault();
  hopscotch.startTour(data[$(this).data('name')]);
}

或者,在属性本身中内联数据可能是有意义的:

<子> HTML:
<a href="#" class="hopscotch-start" data-hopscotch='{"id":"tour1","steps":[{"title":"the title",...}...]'>Start tour</a>
<子> JS:
$("a.hopscotch-start").click(function (e) {
  e.preventDefault();
  hopscotch.startTour($(this).data('hopscotch'));
}

答案 1 :(得分:0)

为什么不制作一个物品并通过钥匙获取?它会更快更安全:

var tours = {
  x: {id: "tour1", steps: [{title: "the title",....}]},
  y: {id: "tour2", steps: [{title: "the title",....}]}
}
$("a.hopscotch-start").click(function (e) {
  e.preventDefault();
  hopscotch.startTour(tours[$(this).data('name')]); // -> startTour(x);
  return false;
}