Chrome Downloads API http requests are not getting modified by Declarative Net Request API

61 Views Asked by At

I am trying to build an extension which uses chrome's Declarative Net Request API to modify my request headers to add forbidden headers. All my HTTP requests to the external website using standard fetch are getting properly modified as expected. However, when I try to download a file using chrome's Downloads API, the download request is not getting modified and hence fails.

Following is my code:

manifest.json

{
  "background": {
    "service_worker": "bg_script.js",
    "type": "module"
  },
  "permissions": ["tabs", "downloads", "declarativeNetRequest", "offscreen"],
  "host_permissions": ["https://*.example.com/*"],
  "declarative_net_request": {
    "rule_resources": [
      {
        "enabled": true,
        "id": "static_ruleset",
        "path": "staticruleset.json"
      }
    ]
  }
}

staticruleset.json

{
  "id": 6413,
  "priority": 3,
  "action": {
    "type": "modifyHeaders",
    "requestHeaders": [
      { "header": "Origin", "operation": "remove" },
      {"header": "Sec-Fetch-Site", "operation": "set", "value": "same-origin" },
      { "header": "Sec-Fetch-Mode", "operation": "set", "value": "navigate" },
      { "header": "Sec-Fetch-Dest", "operation": "set", "value": "document" },
      { "header": "Sec-Fetch-User", "operation": "set", "value": "?1" }
    ]
  },
  "condition": {
    "urlFilter": "example.com/downloads/",
    "resourceTypes": ["xmlhttprequest", "main_frame", "other"]
  }
}

bg_script.js

chrome.downloads.download({
  url: "https://www.example.com/downloads/test.zip",
  method: "GET",
  headers: [
    {
      name: "Accept",
      value: "application/json, text/plain, */*",
    },
  ],
  filename: "test_file.zip",
  conflictAction: "uniquify",
});

If I use downloads API as above, the request is not getting modified as mentioned in the static rule. However, if I trigger the download from DOM, the request is getting modified properly.

offscreen.js

const anchorEl = document.createElement("a");
anchorEl.setAttribute("target", "_blank");
anchorEl.addEventListener("click", () => false);
document.querySelector("body")?.appendChild(anchorEl);
anchorEl.href = "https://www.example.com/downloads/test.zip";
anchorEl.click();
document.querySelector("body")?.removeChild(anchorEl);

I have verified this behavior using chrome://net-export and netlog_viewer. I am finding it difficult to manage the download if it is triggered through DOM and would like to use Downloads API in this case.

is there any workaround to use Downloads API and modify forbidden headers?

0

There are 0 best solutions below