【问题标题】:Chrome extension: Uncaught Error: Code generation from strings disallowed for this contextChrome 扩展:未捕获的错误:此上下文不允许从字符串生成代码
【发布时间】:2012-08-15 11:07:41
【问题描述】:

我正在尝试在 chrome 扩展中使用 micro template engine 并收到以下错误:Uncaught Error: Code generation from strings disallowed for this context 在解析模板时。你能帮我解决这个问题吗?

Manifest.json

manifest.json:
{
  "name": "YYYY",
  "version": "1.0",
  "manifest_version": 2,
  "description": "The first extension that I made.",
  "browser_action": {
    "default_icon": "icon.ico",
    "default_popup": "popup.html"
  }
}

popup.html:

<!doctype html>
<html ng-csp ng-app>
  <head>
    <title>Getting Started Extension's Popup</title>
    <style>
      body {
        min-width:357px;
        overflow-x:hidden;
      }
    </style>

    <!-- JavaScript and HTML must be in separate files for security. -->
    <script src="jquery.min.js"></script>
    <script src="popup.js"></script>


  </head>
  <body>
      <ul>
            <li></li>
      </ul>

        <script id="userlisttemplate" type="text/html">
           <% for(var i=0; i < items.length; i++) { var item = items[i]; %>               

                <li> 
                <%= item.UserName%>

                </li>                                                     

           <% } %>
        </script>
  </body>
</html>

popup.js:

// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function () {
    var cache = {};

    this.tmpl = function tmpl(str, data) {
        // Figure out if we're getting a template, or if we need to
        // load the template - and be sure to cache the result.
        var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :

        // Generate a reusable function that will serve as a template
        // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +

        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +

        // Convert the template into pure JavaScript
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");

        // Provide some basic currying to the user
        return data ? fn(data) : fn;
    };
})();


$.ajax({
    url: myurl,
    type: "GET",
    contentType: "application/json",
    success: function (response) {
        debugger;
        console.log(response);
        var data = response.data;
        var s = tmpl($('#userlisttemplate').html(), { items: data });
        $('body').append($(s));
    },
    error: function (jqXHR, textStatus, errorThrown) {
        $("#result").text(textStatus);
    }
});

【问题讨论】:

    标签: jquery google-chrome google-chrome-extension template-engine


    【解决方案1】:

    此模板库不能在常规扩展程序页面中使用,因为它使用带有字符串的 new Function(),现在 Chrome 的新内容安全策略禁止使用清单版本 2 创建的扩展程序。see here

    【讨论】:

      【解决方案2】:

      你使用的 tmpl 函数不正确,试试这个:

      var s = tmpl('userlisttemplate', { items: data });
      

      同样在您的模板中,您希望 items 是一个数组,但返回的 json 是一个对象(除非 manifest.json 不是实际请求的 json,在这种情况下我需要返回的数据)

      manifest.json 也不包含模板中提到的任何UserName

      尝试以下我确实得到了结果:

      var s = tmpl('userlisttemplate',{
              items: [{
                  "UserName": "test1"
              },{
                  "UserName": "test2"
              },{
                  "UserName": "test3"
              }]
      });
      $('body').append($(s));
      

      【讨论】:

      • at + "');}return p.join('');");在 popup.js 中
      • Chrome 扩展程序:未捕获的错误是安全问题,而不是您所指的问题
      【解决方案3】:

      不要在 popup.html 中使用内部脚本。见Content Security Policy

      【讨论】:

      【解决方案4】:

      尝试用"function(){}" 替换"new Function" 的所有实例,它使我的socket.io.js 工作。

      【讨论】:

        猜你喜欢
        • 2021-04-08
        • 1970-01-01
        • 2013-06-12
        • 1970-01-01
        • 2015-03-14
        • 2017-09-05
        • 2020-10-27
        • 2017-05-17
        • 1970-01-01
        相关资源
        最近更新 更多