[javascript] Refused to apply inline style because it violates the following Content Security Policy directive

So, in about 1 hour my extensions failed hard.

I was doing my extension and it was doing what I pretended. I made some changes, and as I didnt liked I deleted them, and now my extension is throwing error:

Refused to apply inline style because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'style-src' was not explicitly set, so 'default-src' is used as a fallback.

What causes this error?

I made my changes in:

popup.html

<!DOCTYPE html>
<html ng-app="PinIt" ng-csp>
    <head>
        <link rel="stylesheet" href="css/popup.css">
        <script src="js/lib/jquery-1.8.2.min.js"></script>
        <script src="js/lib/angular.min.js"></script>
        <script src="js/app/app.js"></script>
        <script src="js/app/popup.js"></script> 
    </head>
    <body id="popup">
        <header>
            <h1>PinIt</h1>
        </header>
    <div ng-controller="PageController">
            <div>{{message}}</div>
            <h2>Page:</h2>
            <div id="elem">{{title}}</div>
            <div>{{url}}</div>
            <h2>Imagens:</h2>
            <ul>
                <li ng-repeat="pageInfo in pageInfos" style="list-style: none">
                    <div class="imgplusshare">
                    <img src={{pageInfo}} class="imagemPopup"/>
                    <ul class="imas">
                      <li id="liFacebook" ng-click="fbshare(pageInfo)">
                      <span>
                      <img src="facebook_16.png"/>Facebook
                      </span>
                    </li>
                    <li id="liTwitter" ng-click="twshare(pageInfo)">
                    <span>
                    <img src="twitter-bird-16x16.png"/>Twitter
                    </span>
                    </li>
                    <li id="liGooglePlus" ng-click="gpshare(pageInfo)">
                    <span><img src="gplus-16.png"/>Google+</span>
                    </li>
                    <li id="liEmail" ng-click="mailshare(pageInfo)">
                    <span><img src="mail_icon_16.png"/>Email</span>
                    </li>
                    <hr>
                    </ul>

                    </div>
                    </li>

                    </ul>
</div>
    </body>
</html>

popup.js

  myApp.service('pageInfoService', function() {
        this.getInfo = function(callback) {
            var model = {};

            chrome.tabs.query({'active': true},
            function (tabs) {
                if (tabs.length > 0)
                {
                    model.title = tabs[0].title;
                    model.url = tabs[0].url;

                    chrome.tabs.sendMessage(tabs[0].id, { 'action': 'PageInfo' }, function (response) {

                        model.pageInfos = response;

                        callback(model);
                    });

                }

            });
        };
    });
    myApp.controller("PageController", function ($scope, pageInfoService) {

        pageInfoService.getInfo(function (info) {           
            $scope.title = info.title;
            $scope.url = info.url;
            $scope.pageInfos = info.pageInfos;
            $scope.fbshare =  function($src) {
             chrome.windows.create({url:"http://www.facebook.com/sharer/sharer.php?u="+$src});
      };    
            $scope.twshare =  function($src) {
             chrome.windows.create({url:"https://twitter.com/intent/tweet?url="+$src});
      };
            $scope.gpshare =  function($src) {
             chrome.windows.create({url:"https://plus.google.com/share?url="+$src});
      };
            $scope.mailshare =  function($src) {
             chrome.windows.create({url:"mailto:?subject=Imagem Partilhada por PinIt&body=<img src=\""+$src+"\"\\\>"});
      };



            $scope.$apply();


        });
    });

Here is my manifest file:

{
    "name": "PinIt",
    "version": "1.0",
    "manifest_version": 2,

    "description": "Pin It",
    "icons": {
        "128": "icon128.png"
    },
    "browser_action": {
        "default_icon": "img/defaultIcon19x19.png",
        "default_popup": "popup.html",
        "default_title": "PinIt"
    },
    "content_scripts": [ {
    "js": [ "js/lib/jquery-1.8.2.min.js", "js/app/content.js", "js/jquery-ui-1.10.3.custom.js" ],
    "matches": [ "*://*/*" ],
    "run_at": "document_start"
    } ],
    "minimum_chrome_version": "18",
    "permissions": [ "http://*/*", "https://*/*", "unlimitedStorage", "contextMenus", "cookies", "tabs", "notifications" ],
    "content_security_policy": "default-src 'self'"
}

any sugestion?

The answer is


You can also relax your CSP for styles by adding style-src 'self' 'unsafe-inline';

"content_security_policy": "default-src 'self' style-src 'self' 'unsafe-inline';" 

This will allow you to keep using inline style in your extension.

Important note

As others have pointed out, this is not recommended, and you should put all your CSS in a dedicated file. See the OWASP explanation on why CSS can be a vector for attacks (kudos to @ KayakinKoder for the link).


As the error message says, you have an inline style, which CSP prohibits. I see at least one (list-style: none) in your HTML. Put that style in your CSS file instead.

To explain further, Content Security Policy does not allow inline CSS because it could be dangerous. From An Introduction to Content Security Policy:

"If an attacker can inject a script tag that directly contains some malicious payload .. the browser has no mechanism by which to distinguish it from a legitimate inline script tag. CSP solves this problem by banning inline script entirely: it’s the only way to be sure."


As per http://content-security-policy.com/ The best place to start:

    default-src 'none'; 
    script-src 'self'; 
    connect-src 'self'; 
    img-src 'self'; 
    style-src 'self';
    font-src 'self';

Never inline styles or scripts as it undermines the purpose of CSP. You can use a stylesheet to set a style property and then use a function in a .js file to change the style property (if need be).


Another method is to use the CSSOM (CSS Object Model), via the style property on a DOM node.

var myElem = document.querySelector('.my-selector');
myElem.style.color = 'blue';

More details on CSSOM: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.style

As mentioned by others, enabling unsafe-line for css is another method to solve this.


Well, I think it is too late and many others have the solution so far.

But I hope this can Help:

I'm using react for an identity server so 'unsafe-inline' is not an option at all. If you look at your console and actually read the CSP docs, you might find that there are three options for solving the issue:

  1. 'unsafe-inline' as it says is unsafe if your project is using CSPs is for one reason and it is like throwing out the complete policy, will be the same to no have CSP policy at all

    1. 'sha-XXXCODE' this is good, safe but not optimal because there is a lot of manual work and every compilation the SHA might change so it will become easily a nightmare, use only when the script or style is unlikely to change and there are few references

    2. Nonce. This is the winner!

Nonce works in the similar way as scripts

CSP HEADER ///csp stuff nonce-12331

<script nonce="12331">
   //script content
</script>

Because the nonce in the csp is the same that the tag, the script will be executed

In the case of inline styles, the nonce also came in the form of attribute so the same rules apply.

so generate the nonce and put it on your inline scritps

If you are using webpack maybe you are using the style-loader

the following code will do the trick


module.exports = {
  module: {
    rules: [
      {
        test: /\.css$/i,
        use: [
          {
            loader: 'style-loader',
            options: {
              attributes: {
                nonce: '12345678',
              },
            },
          },
          'css-loader',
        ],
      },
    ],
  },
};


You can use in Content-security-policy add "img-src 'self' data:;" And Use outline CSS.Don't use Inline CSS.It's secure from attackers.


Questions with javascript tag:

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax Drag and drop menuitems Is it possible to execute multiple _addItem calls asynchronously using Google Analytics? DevTools failed to load SourceMap: Could not load content for chrome-extension TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app What does 'x packages are looking for funding' mean when running `npm install`? SyntaxError: Cannot use import statement outside a module SameSite warning Chrome 77 "Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6 Why powershell does not run Angular commands? Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop Push method in React Hooks (useState)? JS file gets a net::ERR_ABORTED 404 (Not Found) React Hooks useState() with Object useState set method not reflecting change immediately Can't perform a React state update on an unmounted component UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block Can I set state inside a useEffect hook internal/modules/cjs/loader.js:582 throw err How to post query parameters with Axios? How to use componentWillMount() in React Hooks? React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory in ionic 3 How can I force component to re-render with hooks in React? What is useState() in React? How to call loading function with React useEffect only once Objects are not valid as a React child. If you meant to render a collection of children, use an array instead How to reload current page? Center content vertically on Vuetify Getting all documents from one collection in Firestore ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment How can I add raw data body to an axios request? Sort Array of object by object field in Angular 6 Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Axios Delete request with body and headers? Enable CORS in fetch api Vue.js get selected option on @change Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) Angular 6: How to set response type as text while making http call

Questions with google-chrome-extension tag:

How to change the locale in chrome browser How to download PDF automatically using js? Install Chrome extension form outside the Chrome Web Store Google Chromecast sender error if Chromecast extension is not installed or using incognito Getting "net::ERR_BLOCKED_BY_CLIENT" error on some AJAX calls Disable developer mode extensions pop up in Chrome How to use jQuery in chrome extension? How to test REST API using Chrome's extension "Advanced Rest Client" Chrome Extension - Get DOM content Refused to apply inline style because it violates the following Content Security Policy directive Where to find extensions installed folder for Google Chrome on Mac? Checkbox Check Event Listener Where does Chrome store extensions? onclick or inline script isn't working in extension Chrome says my extension's manifest file is missing or unreadable Getting the source HTML of the current page from chrome extension Does mobile Google Chrome support browser extensions? Simulate limited bandwidth from within Chrome? .crx file install in chrome Use a content script to access the page context variables and functions Chrome extension id - how to find it How to save CSS changes of Styles panel of Chrome Developer Tools? Chrome Extension: Make it run every page load Check whether user has a Chrome extension installed Sqlite in chrome How to wait until an element exists? Chrome sendrequest error: TypeError: Converting circular structure to JSON How to simulate key presses or a click with JavaScript? Chrome extension: accessing localStorage in content script google chrome extension :: console.log() from background page? Is there a JavaScript / jQuery DOM change listener? Start an external application from a Google Chrome Extension? How can I get the URL of the current tab from a Google Chrome extension?

Questions with content-security-policy tag:

Content Security Policy: The page's settings blocked the loading of a resource Refused to load the script because it violates the following Content Security Policy directive How does Content Security Policy (CSP) work? Content Security Policy "data" not working for base64 Images in Chrome 28 Refused to apply inline style because it violates the following Content Security Policy directive