4

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

清单.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);
    }
});
4

4 回答 4

2

此模板库不能在常规扩展页面中使用,因为它new Function()与字符串一起使用,现在 Chrome 的新内容安全策略禁止使用清单版本 2 创建的扩展。请参阅此处

于 2012-08-15T21:09:37.237 回答
0

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

于 2012-10-24T22:15:42.097 回答
0

不要在 popup.html 中使用内部脚本。请参阅内容安全策略

于 2012-08-15T13:23:59.817 回答
0

你使用的 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));
于 2012-08-15T11:10:54.957 回答