Can I ask a browser to not run <script>s within an element?

Seppo Ervi&#228;l&#228; picture Seppo Erviälä · Sep 19, 2014 · Viewed 17.2k times · Source

Is it possible to tell browsers to not run JavaScript from specific parts of an HTML document?

Like:

<div script="false"> ...

It could be useful as an additional security feature. All the scripts I want are loaded in a specific part of the document. There should be no scripts in other parts of the document and if there are they should not be run.

Answer

Falco picture Falco · Sep 19, 2014

YES, you can :-) The answer is: Content Security Policy (CSP).

Most modern browsers support this flag, which tells the browser only to load JavaScript code from a trusted external file and disallow all internal JavaScript code! The only downside is, you can not use any inline JavaScript in your whole page (not only for a single <div>). Although there could be a workaround by dynamically including the div from an external file with a different security policy, but I'm not sure about that.

But if you can change your site to load all JavaScript from external JavaScript files then you can disable inline JavaScript altogether with this header!

Here is a nice tutorial with example: HTML5Rocks Tutorial

If you can configure the server to send this HTTP-Header flag the world will be a better place!