AngularJS uses eval in chrome extension

2019-01-29 03:29发布

问题:

The lates AngularJS (1.3 beta 19) uses eval. This is prohibited in chrome extionsion.

How to fix the issue without allowing evals?

Error message:

Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src 'self' chrome-extension-resource:".

Stack trace:

angular.js:1011
csp angular.js:1011
(anonymous function) angular.js:23556

UPDATE: See documentation of ng-csp https://docs.angularjs.org/api/ng/directive/ngCsp

OUTDATED: It looks like AngularJS fails to detect CSP in chrome extension. Use explicit ng-csp. Link to the AngularJS issue: https://github.com/angular/angular.js/issues/8777

回答1:

To quote documentation that Dmitry linked:

Angular tries to autodetect if CSP is active and automatically turn on the CSP-safe mode. This autodetection however triggers a CSP error to be logged in the console:

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'". Note that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.

This error is harmless but annoying. To prevent the error from showing up, put the ngCsp directive on the root element of the application or on the angular.js script tag, whichever appears first in the html document.



回答2:

Solution found: enforcing CSP mode by adding ng-csp on an element of document.

See documentation of ng-csp https://docs.angularjs.org/api/ng/directive/ngCsp