我所知道的是 eval
、 Function
和 setTimeout
。尽管 setImmediate
引用没有提到它可以用字符串参数调用,但我认为它在这方面的工作方式与 setTimeout
相同。
在浏览器中从字符串评估代码的可能方法是什么(包括非标准方法)?
最佳答案
在浏览器上,我唯一知道的是:
eval
Function
构造函数 setTimeout
和相关( setInterval
,非标准 setImmediate
) document.write
或类似方法) javascript:
伪协议(protocol)(然后人为单击它们或邀请用户这样做)居住:
eval("console.log('eval');");
(0,eval)("console.log('indirect eval');");
new Function("console.log('Function constructor');")();
setTimeout("console.log('setTimeout and such');", 0);
var script = document.createElement("script");
script.textContent = "console.log('script element');";
document.body.appendChild(script);
var link = document.createElement("a");
link.href = "javascript:console.log('javascript: pseudo-protocol');";
document.body.appendChild(link);
link.click();
var div = document.createElement("div");
div.setAttribute("onclick", "console.log('DOM0 event handler');");
document.body.appendChild(div);
div.click();
/* Or to be long-winded
div.dispatchEvent(new MouseEvent("click", {
view: window,
bubbles: true,
cancelable: true
}));
*/
关于javascript - 执行 eval 的可能方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50297097/