1

I recently discovered that its possible to run javascript from an <a> tag like this

<a href="javascript:alert('test')">

and this gets run on the current page when clicked. It also seems to run in the context of the page it was clicked on and has access to the websites local storage. I want to prevent this from happening. I can see CSP can be used to block inline javascript blocks but I can't see if this includes these javascript links.

Would adding a CSP header prevent these JS links from working?

2

Your question can be answered with a simple test using some local HTML file:

<meta http-equiv="Content-Security-Policy" content="script-src 'self'">
<a href="javascript:alert('test')">click me</a>

When trying to click on the link no Javascript gets executed. Looking at the console in Chrome's developer tools one can see:

Refused to run the JavaScript URL because it violates the following Content Security Policy directive: "script-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-...'), or a nonce ('nonce-...') is required to enable inline execution.

When adding unsafe-inline as suggested it instead works as expected, i.e. the script gets executed:

<meta http-equiv="Content-Security-Policy" content="script-src 'self' 'unsafe-inline'">
<a href="javascript:alert('test')">click me</a>

Also, from the documentation of CSP:

'unsafe-inline'
Allows the use of inline resources, such as inline elements, javascript: URLs, inline event handlers, and inline elements. You must include the single quotes

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.