Function button to take a screenshot and download it as an image file

232 Views Asked by At

I'm trying to develop a button that simply takes a screenshot of the current tab and downloads it (this may seem useless, as we can take screenshots manually, but I plan to extend the button's functionalities to make more things). I am using Firefox 116.0.1 (64-bit).

The code associated to the button is as follows:

function takeScreenshotAndSave() 
{
  browser.tabs.captureVisibleTab({ format: "png" })
    .then(screenshotUrl => {
      console.log("Screenshot URL:", screenshotUrl);
      const filename = `Capture-snapshot${Date.now()}-visible-1.png`;

      browser.downloads.download({
        url: screenshotUrl,
        filename: filename,
        conflictAction: "uniquify",
      });
    })
    .catch(error => {
      console.error("Error taking screenshot:", error);
    });
}

This works well until we reach the "browser.downloads.download" part, where I get an error:

Error taking screenshot: Error: Type error for parameter options (Error processing url: Error: Access denied for URL data:,) for downloads.download.

In my manifest.json file, I have the following permissions:

  "permissions": [
    "notifications",
    "activeTab",
    "downloads",
    "<all_urls>"
  ],

So I have the "<all_urls>" permission, but this does not seem to be enough. I tried to follow the suggestions at Save Data URI as file using downloads.download() API concerning the creation of a blob, but if I do that I end up with a file containing the "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABy0AAANzCAY ..." string, not the real .png file.

I'm stuck here. Any suggestion is welcome.

1

There are 1 best solutions below

2
ManuelMB On

I made your code works as follows:

Error: Permission '<all_urls>' is unknown or URL pattern is malformed.

Solution: Site/URL permissions in ManifestV3 use a separate key: host_permissions

  • manifest.json

      "host_permissions": ["http://*/*", "https://*/*"],    
      "permissions": [  
          "notifications",
          "activeTab",
           "downloads"
       ],
    

Error in event handler: ReferenceError: browser is not defined at takeScreenshotAndSave

Solution: In your function takeScreenshotAndSave() replace browser for chrome:

  • background.js

      function takeScreenshotAndSave(){
        chrome.tabs.captureVisibleTab({ format: "png" })
          .then(screenshotUrl => {
             console.log("Screenshot URL:", screenshotUrl);
             const filename = `Capture-snapshot${Date.now()}-visible-1.png`;
             chrome.downloads.download({
                url: screenshotUrl,
                filename: filename,
                conflictAction: "uniquify",
              });
      })
      .catch(error => {
        console.error("Error taking screenshot:", error);
      });
    

    }