如何从另一个网址下载文件与MV3 chrome 扩展名?

vxbzzdmp  于 2023-01-10  发布在  Go
关注(0)|答案(2)|浏览(241)

我正在使用MV 3创建一个chrome扩展,它会在文档正文中插入一个下载按钮。我尝试使用该下载按钮下载另一个URL上的示例PDF,但无法执行此操作。当我单击该按钮时,Chrome只会在当前选项卡中打开PDF。我需要将其像普通文件一样下载到计算机。我在清单中拥有下载权限,但我不确定我做错了什么。任何帮助将不胜感激!
这是我的contentScript.JS文件中存储下载按钮的位置。

function createModal() {
            var auroraModal = document.createElement('div');
            auroraModal.className = '_aurora__modal';
            auroraModal.id = '_aurora__modal';

            var downloadLink = document.createElement('a');
            downloadLink.download = "Example.pdf";
            downloadLink.href = "https://www.africau.edu/images/default/sample.pdf";
            downloadLink.innerHTML = 'Download';

            auroraModal.innerHTML = '<p>Woo-hoo <strong>'+dataFromPromise+'</strong>! Your custom PDF is ready!</p>';
            auroraModal.appendChild(downloadLink)
            document.body.appendChild(auroraModal)
        }

这是我的载货单

{
  "name": "Aurora Extension",
  "manifest_version": 3,
  "description": "Aurora extension attempt with FB9 and MV3",
  "permissions": ["storage", "tabs", "downloads"],
  "host_permissions": ["https://*.stackoverflow.com/*"],
  "background": { "service_worker": "background/index.js" },
  "content_scripts": [
    {
      "js": ["content/index.js"],
      "css": ["content/coupon.css"],
      "matches": ["https://*.stackoverflow.com/*"]
    }
  ],
  "action": { "default_popup": "pages/popup/index.html" }
}
lokaqttq

lokaqttq1#

请使用chrome.downloads.download
manifest.json

{
  "name": "chrome.downloads.download",
  "version": "1.0",
  "manifest_version": 3,
  "permissions": [
    "downloads"
  ],
  "action": {
    "default_popup": "popup.html"
  }
}

popup.html

<html>
<body>
  <script src="popup.js"></script>
</body>
</html>

popup.js

chrome.downloads.download({
  filename: "Example.pdf",
  url: "https://www.africau.edu/images/default/sample.pdf"
});
vd2z7a6w

vd2z7a6w2#

这使用了content scriptsservice worker
manifest.json

{
  "name": "chrome.downloads.download used content_scripts + service_worker",
  "version": "1.0",
  "manifest_version": 3,
  "permissions": [
    "downloads"
  ],
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "js": [
        "matches.js"
      ],
      "matches": [
        "<all_urls>"
      ]
    }
  ]
}

matches.js

console.log("matches.js");

const button = document.createElement("button");
button.innerText = "button";

button.onclick = () => {
  chrome.runtime.sendMessage("");
  console.log("Send");
}

document.body.insertBefore(button, document.body.firstElementChild);

background.js

console.log("background.js");

chrome.runtime.onMessage.addListener(() => {
  console.log("Receive");
  chrome.downloads.download({
    filename: "Example.pdf",
    url: "https://www.africau.edu/images/default/sample.pdf"
  });
});

相关问题