CSP and javascript:void(0) links

What the heck does that mean?

A bit of background, first. I was chatting to Paul Usher the other day about using onclick() calls within anchor elements. Usually that is coded something like

<a onclick="doSomething()" href="javascript:void(0);">Click me to do something!</a>

Basically the void operator (it’s not a function: void(0) is the same as void 0) always returns undefined, so the browser, in evaluating the URL for the href parameter, gets undefined and doesn’t try to follow a link. Instead, what happens is the onclick handler does its stuff. In other words, the anchor element is not actually providing a link to follow, but instead is just some element on the page that will process a mouse click.

Now me, I never use this construct. Instead I’d use a button element instead. Yeah, I’d have to change its style so that it resembles a clickable link, but that’s fine.

The problem in using this construct occurs if you use a Content Security Policy for the website. The CSP basically is the way to protect the site from XSS attacks. You define from where exactly the site will load scripts, images, styles, fonts, etc and this minimizes loading malicious assets. As an example, here’s the CSP from the web.config for one of my websites:

<rule name="CSP">
  <match serverVariable="RESPONSE_Content-Security-Policy" pattern=".*" />
  <action type="Rewrite" value="default-src 'self'; 
    script-src 'self' https:; 
    img-src 'self' https:; 
    style-src 'self' https:; 
    font-src 'self' https:;" />
</rule>

Now if I did have this “bad” style of anchor element that I started with and the user clicked it, here’s the error the browser console would report:

Content Security Policy: The page’s settings blocked the loading of a resource at inline (“script-src”).

In other words that call to void is blocked, and the href is not evaluated. If you really did want to remove that error and allow inline scripts you could add 'unsafe-inline' to your script-src CSP directive.

And if that name doesn’t make you pause and decide not to, why are you reading this post?

Locks on Bridge

Loading similar posts...   Loading links to posts on similar topics...

No Responses

Feel free to add a comment...

Leave a response

Note: some MarkDown is allowed, but HTML is not. Expand to show what's available.

  •  Emphasize with italics: surround word with underscores _emphasis_
  •  Emphasize strongly: surround word with double-asterisks **strong**
  •  Link: surround text with square brackets, url with parentheses [text](url)
  •  Inline code: surround text with backticks `IEnumerable`
  •  Unordered list: start each line with an asterisk, space * an item
  •  Ordered list: start each line with a digit, period, space 1. an item
  •  Insert code block: start each line with four spaces
  •  Insert blockquote: start each line with right-angle-bracket, space > Now is the time...
Preview of response