我第一次写了一个 Firefox 插件,几个月前它被审查并接受了。此插件经常调用第三方 API。同时它再次被审查,现在它调用 setInterval 的方式受到批评:
setInterval
以潜在危险的方式调用。为了防止漏洞,setTimeout 和 setInterval 函数只能以函数表达式作为它们的第一个参数来调用。引用函数名称的变量是可接受的,但不推荐使用,因为它们不适合静态源代码验证。
这里有一些关于我的插件的»架构«的背景。它使用一个全局对象,它只不过是一个命名空间:
if ( 'undefined' == typeof myPlugin ) {
var myPlugin = {
//settings
settings : {},
intervalID : null,
//called once on window.addEventlistener( 'load' )
init : function() {
//load settings
//load remote data from cache (file)
},
//get the data from the API
getRemoteData : function() {
// XMLHttpRequest to the API
// retreve data (application/json)
// write it to a cache file
}
}
//start
window.addEventListener(
'load',
function load( event ) {
window.removeEventListener( 'load', load, false ); needed
myPlugin.init();
},
false
);
}
所以这可能不是最好的做法,但我一直在学习。间隔本身在init()
方法内部被调用,如下所示:
myPlugin.intervalID = window.setInterval(
myPlugin.getRemoteData,
myPlugin.settings.updateMinInterval * 1000 //milliseconds!
);
还有一点设置间隔:设置(首选项)的观察者清除当前间隔,并在 updateMinInterval 设置发生更改时以与上面提到的完全相同的方式设置它。
当我做对了,使用»函数表达式«的解决方案应该如下所示:
myPlugin.intervalID = window.setInterval(
function() {
myPlugin.getRemoteData();
},
myPlugin.settings.updateMinInterval * 1000 //milliseconds!
);
我对吗?
到目前为止,我忽略了“攻击”此代码的可能场景是什么?
应该setInterval
并且setTimeout
基本上以另一种方式在 Firefox 插件中使用,然后在 »normal« 前端 javascripts 中使用?因为setInterval的文档在某些示例中准确地显示了使用声明函数的方式。