Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Page Specific JavaScript using Content Security Policy (CSP) [duplicate]

I want to use Content Security Policy (CSP) across my entire site. This requires all JavaScript to be in separate files. I have shared JavaScript used by all pages but there is also page specific JavaScript that I only want to run for a specific page. What is the best way to handle page specific JavaScript for best performance?

Two ways I can think of to workaround this problem is to use page specific JavaScript bundles or a single JavaScript bundle with switch statement to execute page specific content.

like image 913
Muhammad Rehan Saeed Avatar asked Apr 26 '17 07:04

Muhammad Rehan Saeed


People also ask

How does Content-Security-Policy CSP work?

Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross-Site Scripting (XSS) and data injection attacks. These attacks are used for everything from data theft, to site defacement, to malware distribution.

How do I fix the Content-Security-Policy of your site blocks the use of eval in JavaScript?

The Content Security Policy (CSP) prevents the evaluation of arbitrary strings as JavaScript to make it more difficult for an attacker to inject unauthorized code on your site. To solve this issue, avoid using eval() , new Function() , setTimeout([string], ...) and setInterval([string], ...) for evaluating strings.

How do I stop Content-Security-Policy?

Click the extension icon to disable Content-Security-Policy header for the tab. Click the extension icon again to re-enable Content-Security-Policy header. Use this only as a last resort. Disabling Content-Security-Policy means disabling features designed to protect you from cross-site scripting.


1 Answers

there is lots of ways to execute page specific javascript

Option 1 (check via class)

Set a class to body tag

<body class="PageClass">

and then check via jQuery

$(function(){
  if($('body').hasClass('PageClass')){
    //your code
  }
});

Option 2 (check via switch case)

var windowLoc = $(location).attr('pathname'); //jquery format to get window.location.pathname

switch (windowLoc) {
    case "/info.php":
        //code here
        break;
    case "/alert.php":
        //code here
        break;
}

Option 3 Checking via function

make all the page specific script in the function

function homepage() {
    alert('homepage code executed');
}

and then run function on specific page

homepage();
like image 139
Ismail Farooq Avatar answered Oct 20 '22 21:10

Ismail Farooq