CSP solution for multiple inline scripts

548 views Asked by At

So... CSP is implemented successfully on my site. However - my website use many inline scripts to redirect visitors depending on their HTML checkbox selections. In development, unsafe-inline has sufficed, but I'm now ready to go live and this is a big roadblock preventing me from doing so.

<label for="giorgio-armani" class="d-flex">
<input type="checkbox" id="giorgio-armani" class="mr-2 mt-1" onChange="window.location.href='/shop/brands/giorgio-armani'"> Giorgio Armani</label>

This would be an example of my code. As it's for a site menu, there can be literally hundreds of the same checkboxes in a row to different destinations.

I did have a solution link bookmarked to allow me to return to this at a later date, but I appear to have deleted it...

All help appreciated!

1

There are 1 answers

3
Taplar On

One approach is to remove the need for the inline event bindings and make them dynamically with your scripts. Such as...

<label for="giorgio-armani" class="d-flex">
    <input type="checkbox"
           id="giorgio-armani"
           class="goto mr-2 mt-1"
           data-target="/shop/brands/giorgio-armani"
    >
    Giorgio Armani
</label>
document.body.addEventListener('change', e => {
  if (e.target && e.target.classList.contains('goto')) {
    window.location.href = e.target.dataset.target;
  }
});

So lets look at this.

  1. The input now has a goto class on it, signifying that this is an element that we have generalized to behave in the manner that we want. In this case, it needs to change what page we are on.
  2. The input also has a data-target attribute on it. We use this as a data model attribute to hold data related to the "link" that we need in order to perform our page changing logic.
  3. In the script, we create an event handler on the body that listens for any change event for any child it has, now or in the future.
  4. When a change event happens, we test the element the event originated from to see if it has the goto class on it. If it does, we do our work.