Underscore.js _.template causes error from Chrome extension

后端 未结 6 666
北荒
北荒 2020-12-16 12:52

If I use underscore.js\'s _.template() from inside a Google Chrome extension I get the following error in the console:

Uncaught Error: Code generation

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-16 13:45

    Manifest v2 limitations, as said above, forbid to use Eval, new Function, and inline scripts - even when playing with the Content Security Policy: there's no way to relax this security policy in v2 extensions.

    Most template libraries use, at some point or another, evals. One solution is to rewrite your extensions so that all logic resides in a javascript, and nothing in a template; a solution such as google jstemplate should in this case be usable.

    There's, though, the option to do Eval and new Function inside a sandboxed iframe, for instance with the following lines in the manifest:

    "sandbox": {
        "pages": [
          "page1.html",
          "directory/page2.html"
        ]
    },
    

    A sandboxed page will not have access to extension or app APIs, or direct access to non-sandboxed pages (it may communicate with them via postMessage()). You can further restrict the sandbox rights with a specific CSP

    There's now a full example from the Google Chrome team on the github eval in iframe on how to circumvent the problem by communicating with a sandboxed iframe, as well as a short analytics tutorial

    Hopefully some library will show up using this mechanism to provide full compatibility with standard templates usage, though I'd advise removing as much logic from the templates as possible for performance reasons...

    Thanks to Google, there's a lot of extension rewriting in the lineup :(

提交回复
热议问题