Chrome Extension: How do I use declarativeNetRequest to bypass the Content Security Policy

1.9k Views Asked by At

I'm making an extension that injects a user provided script into the current website. I've gotten that part done (with the help of wOxxOm). Only problem is that on some websites, it doesn't work. It throws this error in the console: Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self'. I have been trying to fix this using declarativeNetRequest, however it's not working.

rule1.json

[
    {
        "id": 1,
        "priority": 1,
        "action": {
            "type": "modifyHeaders",
            "responseHeaders": [
                {
                    "header": "content-security-policy",
                    "operation": "remove"
                }
            ]
        },
        "condition": {
            "urlFilter": "*://*/*",
            "resourceTypes": ["main_frame"]
        }
    }
]

manifest.json

{
    ...
    "permissions": ["scripting", "activeTab", "declarativeNetRequest"],
    ...
    "declarative_net_request": {
        "rule_resources": [
            {
                "id": "ruleset_1",
                "enabled": true,
                "path": "/rules/rule1.json"
            }
        ]
    }
}

Javascript

let button = document.getElementById("run");
button.addEventListener("click", async () => {
    let input = document.getElementById("script");
    let script = input.value;
    await execInPage(script);
});
async function execInPage(code) {
    const [tab] = await chrome.tabs.query({ currentWindow: true, active: true });
    chrome.scripting.executeScript({
        target: { tabId: tab.id },
        func: (code) => {
            const el = document.createElement("script");
            el.textContent = code;
            document.head.appendChild(el);
        },
        args: [code],
        world: "MAIN",
    });
}

I am using manifest v3. The extension has not been published yet. I am using developer mode for now.

3

There are 3 best solutions below

1
T0massDev1 On

It doesn't seem to work on websites that use the element to set CSP. Anyone has another solution?

1
user20652129 On

Did you publish it on Chrome Web Store? I was wondering if Google accepted the code because MV3 doesn't allow to use any remotely hosted code. Remotely hosted code restrictions

1
Mikhail Razgovorov On

rule_remove_csp.json

[
  {
    "id": 11,
    "priority": 1,
    "action": {
      "type": "modifyHeaders",
      "responseHeaders": [
        {
          "header": "X-Frame-Options",
          "operation": "remove"
        },
        {
          "header": "Content-Security-Policy",
          "operation": "remove"
        }
      ]
    },
    "condition": {
      "resourceTypes": [
        "main_frame"
      ]
    }
  }
]