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?
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.
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.
Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With