Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore.js _.template causes error from Chrome extension

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 from strings disallowed for this context

Is there any way to get past this error?

like image 330
djmccormick Avatar asked Jan 10 '12 17:01

djmccormick


People also ask

What is underscore template?

The _. template() function is an inbuilt function in the Underscore. js library of JavaScript which is used to compile JavaScript templates into functions that can be evaluated for rendering. Useful for rendering complicated bits of HTML from JSON data sources.

What is underscore js used for?

Underscore. js is a utility library that is widely used to deal with arrays, collections and objects in JavaScript. It can be used in both frontend and backend based JavaScript applications. Usages of this library include filtering from array, mapping objects, extending objects, operating with functions and more.

What is underscore js library?

Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects.


2 Answers

Many thanks to the Chromium list contributor who pointed out that to create a Function object in the way underscore is doing it requires the manifest.json option for content_security_policy to include 'unsafe-eval'.

As an example, your manifest.json could be

{
  "manifest_version": 2,
  ...
  "content_security_policy": "script-src 'self' 'unsafe-eval'",
  ...
}

and then the underscore behavior would work because this policy allows it. For more information on the format see the Chrome documentation on this option here.

like image 91
djmccormick Avatar answered Sep 23 '22 18:09

djmccormick


Unfortunately I don't think you can use underscore.js's _.template() from within a chrome extension...at least with the new manifest.json version 2. The same holds true for trying to use the jQuery Template plugin.

From the Google Chrome Extension's Content Security Policy page:

There is no mechanism for relaxing the restriction against executing inline JavaScript. In particular, setting a script policy that includes unsafe-inline will have no effect. This is intentional.

I am going to look at other templating engines that will hopefully not use the new Function object.

like image 27
Andrew Brown Avatar answered Sep 21 '22 18:09

Andrew Brown