如何在Manifest版本2中使用Backbone.js模板进行Chrome扩展

Der*_*mbo 5 javascript google-chrome google-chrome-extension backbone.js handlebars.js

我试图使用模板作为我的骨干视图.我用underscore.template尝试了它以使其运行.问题是,由于chrome扩展的manifest_version 2存在一些安全限制.我认为原因是因为不再允许内联块.在这个小例子中,我加载一个模板并尝试渲染它.然后我得到错误:

未捕获的错误:对于此上下文不允许从字符串生成代码.

我也尝试使用Handlebars.js和我的html文件中的模板.它适用于普通的浏览器窗口.但它不作为chrome扩展.

那么我如何在带有manifest_version 2的chrome扩展中使用带有backbone.js的模板?

使用下划线(不起作用):

define [
  'jquery'
  'backbone'
  'lib/facade'
  'text!templates/loginTemplate.js'
],
($, Backbone, facade, LoginTemplate) ->
  'use strict'
  class LoginView extends Backbone.View
    tagName: 'div'
    events: {

    }

    initialize: (options) ->
      @el = options.el

    render: ->
      console.log 'LoginView: render()'
      $(@el).html(_.template(LoginTemplate, {}))
Run Code Online (Sandbox Code Playgroud)

带把手(不起作用):

index.html中的模板:

<!-- templates -->
  <script id="loginTemplate" type="text/x-handlebars-template">
    <form class="form-horizontal">
      <fieldset>
        <legend>Login</legend>
        <div class="control-group">
          <label class="control-label" for="email">Email:</label>
          <div class="controls">
            <input type="text" class="input-xlarge" id="email" name="email">
          </div>
        </div>
        <div class="control-group">
          <label class="control-label" for="password">Passwort:</label>
          <div class="controls">
            <input type="password" class="input-xlarge" id="password" name="password">
          </div>
        </div>
        <div class="form-actions">
          <button type="submit" class="btn btn-primary">Login</button>
        </div>
      </fieldset>
    </form>
  </script>
Run Code Online (Sandbox Code Playgroud)

在我看来:

define [
  'jquery'
  'backbone'
  'lib/facade'
],
($, Backbone, facade) ->
  'use strict'
  class LoginView extends Backbone.View
    tagName: 'div'    
    events: {

    }

    initialize: (options) ->
      @el = options.el

    render: ->
      console.log 'LoginView: render()', $("#loginTemplate")
      $(@el).html(Handlebars.compile($("#loginTemplate").html()))
Run Code Online (Sandbox Code Playgroud)

mu *_*ort 3

Underscore 和 Handlebars 模板都将字符串转换为 JavaScript 函数;例如, Underscore 是这样的

source = "var __t,__p='',__j=Array.prototype.join," +
  "print=function(){__p+=__j.call(arguments,'')};\n" +
  source + "return __p;\n";

var render = new Function(settings.variable || 'obj', '_', source);
Run Code Online (Sandbox Code Playgroud)

所以它构建了一些 JavaScript 并用于new Function构建一个函数;车把可能也有类似的作用。显然 Chrome 不希望你在扩展中做类似的事情。

您可以预编译模板,然后将该函数作为简单的 JavaScript 代码嵌入到您的扩展中。对于下划线模板,您可以查看source属性

编译后的模板函数上可以使用 source 属性,以便于预编译

<script>
  JST.project = <%= _.template(jstText).source %>;
</script>
Run Code Online (Sandbox Code Playgroud)

因此,您可以t = _.template(your_template)在打包扩展时将t.source文本作为 JavaScript 函数放入扩展中。

您可以使用 Handlebars 执行类似的操作(例如,请参阅handlebars_assets )。

它们都会使您的构建和打包过程变得复杂,但如果 Chrome 不希望您在扩展中构建函数,那么您无能为力。