代码之家  ›  专栏  ›  技术社区  ›  Guido

在一堆HTML中查找并执行Javascript片段

  •  0
  • Guido  · 技术社区  · 15 年前

    eval 字符串中包含的Javascript代码。

    <script>...</script> 它成立了。

    function executeJs(html) {
        var scriptFragment = "<script(.+?)>(.+?)<\/script>";
        match = new RegExp(scriptFragment, "im");
        var matches = html.match(match);
        if (matches.length >= 2) {
            eval(matches[2]);
        }
    }
    

    我想知道是否有一种方法允许我迭代并执行所有Javascript片段。

    3 回复  |  直到 15 年前
        1
  •  3
  •   Blixt    15 年前

    只需要第一个是因为你错过了 g 旗帜试试这个:

    function executeJs(html) {
        var scriptFragment = '<script(.*?)>(.+?)<\/script>';
        var re = new RegExp(scriptFragment, 'gim'), match;
        while ((match = re.exec(html)) != null) {
            eval(match[2]);
        }
    }
    
    executeJs('<script>alert("hello")</script>abc<script>alert("world")</script>');
    
        2
  •  1
  •   Thiyagaraj    15 年前

    function parseScript(_source)
    {
          var source = _source;
          var scripts = new Array();
    
          // Strip out tags
          while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1)
      {
             var s = source.indexOf("<script");
             var s_e = source.indexOf(">", s);
             var e = source.indexOf("</script", s);
             var e_e = source.indexOf(">", e);
    
             // Add to scripts array
             scripts.push(source.substring(s_e+1, e));
             // Strip from source
             source = source.substring(0, s) + source.substring(e_e+1);
          }
    
          // Loop through every script collected and eval it
          for(var i=0; i<scripts.length; i++)
      {
             try
          {
                 //eval(scripts[i]);
                 if(window.execScript)
                 {
                   window.execScript(scripts[i]); // IE
           }
           else
           {
                   window.setTimeout(scripts[i],0); // Changed this from eval() to setTimeout() to get it in Global scope
                 }
                }
             catch(ex)
          {
                 // do what you want here when a script fails
                 alert("Javascript Handler failed interpretation. Even I am wondering why(?)");
                }
          }
          // Return the cleaned source
          return source;
       }
    
        3
  •  0
  •   Quamis    15 年前