简体   繁体   中英

Trigger functions to be called, while using Content Security Policy in Chrome

I am interested in using CSP , but how can I trigger functions to be called?

I have a Shared .js file, and a long web page, and a short web page. (actually there can be any number of web pages, but I'll keep it here for brevity) Each page has its own function to be called when the page loads. Since inline scripts are not allowed, the JS could just listen for the 'ready' event and then scan for some HTML markers to know which page's function should be used. However there is one limitation to waiting for the 'ready' event, which is applicable for longer pages

At the top of the long web page is a date range filter with a calendar date picker.

<input name="date"/>
<script src="shared.js"></script>
<script>handleCalendarPicker()</script>
.. lots of HTML to load
<script>coolStuff()</script>

In this way, the calendar picker will work almost immediately, even if the page is not finished loading.

Inline scripts are not normally allowed with CSP, but I would still like a way to trigger an event when a certain element is rendered, even prior to the DOM ready event being fired. How can this be accomplished.

Must I use timers with getElementById, or is there a way to trigger an event without allowing arbitrary JS that is normally blocked by CSP?

There are a few ways to accomplish this.

I'm assuming you are allowing self as a script-src.

Rather than having

<script>handleCalendarPicker()</script>

You could have foo.js with

handleCalendarPicker()

inside and then you reference

<script src="foo.js"></script>

Another way is to use the "nonce" attribute. Example adapted from this article .

Content-Security-Policy: script-src 'nonce-EDNnf03nceIOfn39fn3e9h3sdfa'

Then you can mark allowable inline script blocks with the above nonce:

<script nonce=EDNnf03nceIOfn39fn3e9h3sdfa>
  handleCalendarPicker()
</script>

Generate your nonce with a CSPRNG, otherwise any attacker injecting script via XSS would simply use your static nonce. This can be either done on every page request, or once per user session.

Another way is to generate a sha256 hash of your handleCalendarPicker() code. Then simply add this hash to the CSP:

Content-Security-Policy: script-src 'sha256-qznLcsROx4GACP2dm0UCKCzCG-HiZ1guq6ZZDob_Tng='

(Note that the above hash isn't from your code.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM