我所知道的是 evalFunctionsetTimeout 。尽管 setImmediate 引用没有提到它可以用字符串参数调用,但我认为它在这方面的工作方式与 setTimeout 相同。

在浏览器中从字符串评估代码的可能方法是什么(包括非标准方法)?

最佳答案

在浏览器上,我唯一知道的是:

  • eval
  • Function 构造函数
  • setTimeout 和相关( setInterval ,非标准 setImmediate )
  • 创建脚本元素,设置其文本内容,并将其附加到文档中(通过 DOM 方法,或使用 document.write 或类似方法)
  • 在链接等上使用 javascript: 伪协议(protocol)(然后人为单击它们或邀请用户这样做)
  • 书签是这个的一个特例
  • DOM0 事件处理程序(然后人为触发它们或邀请用户这样做)(不错的 GOTO 0 )

  • 居住:

    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/

    10-09 18:21
    查看更多