DEV Community

gurupetach
gurupetach

Posted on

google chrome pdf extension

Am trying to make a google chrome extension that will handle pdf downloads. I want it to send downloaded pdfs to server. Please help. This is what I have currently done. My manifest.json

{
    "name": "PDF333",
    "version": "1.0.1",
    "description": "PDF auto download",
    "manifest_version": 3,
    "author": "Petach",

    "icons": {
        "16":"icons/16.png",
        "32":"icons/32.png",
        "48":"icons/48.png",
        "128":"icons/128.png"
    },
    "permissions": [ "downloads", "activeTab"],
    "background": {
    "service_worker": "background.js"
  }
}
Enter fullscreen mode Exit fullscreen mode

And finally background.js as below

chrome.downloads.onChanged.addListener(function (downloadDelta) {

    if (downloadDelta.state && downloadDelta.state.current === "complete" && downloadDelta.mime === "application/pdf") {
        chrome.downloads.search({ id: downloadDelta.id }, function (downloadItems) {
            var xhr = new XMLHttpRequest();
            xhr.open("POST", "http://localhost:4000");
            xhr.setRequestHeader("Content-Type", "application/pdf");
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200) {
                        console.log("PDF uploaded successfully!");
                    } else {
                        console.error("Failed to upload PDF.");
                    }
                }
            };
            xhr.send(downloadItems[0].filename);
        });
    }
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)