Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I allow `javascript:void(0)` for use in HTML element attributes through Content-Security-Policy?

I want to be able to do

<form action="javascript:void(0)">

or

<a href="javascript:void(0)">

to make sure nothing happens even if the handler fails to prevent the default action. How should I declare this to be allowed using the Content-Security-Policy HTTP response header without resorting to unsafe-eval?

like image 549
Jonas Berlin Avatar asked Sep 22 '17 08:09

Jonas Berlin


People also ask

How do you write JavaScript void 0?

html. Output: Using “javascript:void(0);” in anchor tag: Writing “javascript:void(0);” in anchor tag can prevent the page to reload and JavaScript functions can be called on single or double clicks easily. Example: html.

How do you use JavaScript void?

Combining javascript: and void(0) Using javascript: , you can run code that does not change the current page. This, used with void(0) means, do nothing - don't reload, don't navigate, do not run any code. The "Link" word is treated as a link by the browser.

Where is JavaScript void 0?

JavaScript void 0 means returning undefined (void) as a primitive value. You might come across the term “JavaScript:void(0)” while going through HTML documents. It is used to prevent any side effects caused while inserting an expression in a web page.

Is it safe to use JavaScript void 0?

Generally, you want to avoid href="javascript:void(0)" , as it will cause the browser to parse the value of the link URL, which is both costly and unnecessary. It also introduces a potential XSS security vulnerability, as javascript: URLs violate Content Security Policy (CSP).


1 Answers

I've recently applied CSP policy to a huge VUE project, by adding meta headers to index.html.

Google Chrome would print a warning about javascript: links, but nothing else happens apart from that.

What I did is simply remove the href="javascript: attribute, and added a style to maintain the cursor style:

a:hover {
    cursor: pointer;
}

And it worked great for me.

P.S I also replaced several <a> with <button> tag, and <button> does not require a href attribute.

like image 83
daisy Avatar answered Oct 04 '22 15:10

daisy