marcj/css-element-queries

Support CSP with Nonces

aKzenT opened this issue · 0 comments

Currently using element-queries fails when used with Content Security Policy Level 2 Nonces.

In CSP Level 2 using Nonces require all <script> and <style> elements to have a "nonce" attribute with a random number which is then used in the CSP response header to whitelist the script or style element.

"css-element-queries" creates a style element in its "init" function which of course does not have this "nonce" attribute and will therefore not be allowed to execute.

I propose a simple change that I tested locally which would solve this issue. Instead of always creating a new style element on init the script could look for an existing style-element with a specific identifier and modify this element. So instead of:

cssStyleElement = document.createElement('style');

The script should do something like:

cssStyleElement = document.getElementById('element-queries') || document.createElement('style');

If there is an element with the known id, then it is used, otherwise the existing logic will be used.

This allows users of the package to supply an existing (empty) style-element with a suitable nonce which would be picked up by the libary.

<style id="element-queries" nonce="..."></style>

I tested this successfully locally and did not see any issues with this approach so far. I can create a PR with the change above, if this is suitable for you.