I'm trying to create a chrome packaged app using Angular 2. But I'm getting the following error when I try to run my app:
EvalError: Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "default-src 'self' blob: filesystem: chrome-extension-resource
-> Evaluating chrome-extension://aabbecghjjmmpbagelfmhllgaidcbnmn/app/boot.js
The content of boot.js
is:
System.config({ packages: { app: { format: 'register', defaultExtension: 'js', "defaultJSExtensions": true, } } });
System.import('app/boot').then(null, console.error.bind(console));
I know AngularJS (angular 1) had an ng-csp
directive to fix this Content Security Policy
error. Is there something similair for Angular 2?
Is there a way to run Angular 2 in a packaged app?
Here is the short answer to solving the issue.
Add the following to you Chrome Extension or App Manifest.json
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"
tldr;
Chrome Developer - Extension Content Security Policy (CSP) https://developer.chrome.com/extensions/contentSecurityPolicy
Here's the answer from GitHub
CSP in chrome app with angular 2 #5956 https://github.com/angular/angular/issues/5956#issuecomment-180135425
Here's the issue describe in AngularJS https://docs.angularjs.org/api/ng/directive/ngCsp
So your error message shows that eval
is the issue. Are you using Just-in-Time compilation for your Angular 2 app? I realize this is an old question, but if you use AOT (Ahead-of-Time) compilation, it will not need to use eval
for your templates:
https://angular.io/guide/aot-compiler
Better security
AOT compiles HTML templates and components into JavaScript files long before they are served to the client. With no templates to read and no risky client-side HTML or JavaScript evaluation, there are fewer opportunities for injection attacks.
Another option is to use <webview>
to host your Angular 2 app:
https://developer.chrome.com/apps/tags/webview
With this, the content of your page will not be sandboxed and the CSP requirements of a Chrome App will not apply. However, you will not be able to access the Chrome App APIs directly from your Angular app. The solution to this is to use message passing between your Angular app and the Chrome App that is hosting it. The Angular app sends a message to host, and host invokes Chrome App API and sends results back to Angular app page:
https://developer.chrome.com/apps/app_external#postMessage
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