Webextensions - 可以在后台脚本中从画布下载图像吗?

时间:2018-02-08 14:22:46

标签: javascript canvas firefox-webextensions

我正在使用firefox扩展程序,它允许我以不同的比例下载图像。目前我的脚本如下所示:

图像调整大小-download.js:

var size = 500;

browser.menus.create({
    id: "dl-resized",
    title: 'Download Resized',
    contexts: ["image"]
});

browser.menus.onClicked.addListener((info, tab) => {
    if (info.menuItemId == "dl-resized") {
        var canvas = document.createElement('canvas');
        var cc = canvas.getContext("2d");
        canvas.width = size;
        canvas.height = size;
        var img = new Image();
        document.body.appendChild(canvas);

        img.onload = function () {
            var canvas2 = document.createElement('canvas'),
                cc2 = canvas2.getContext('2d');

            canvas2.width = img.width * 0.5;
            canvas2.height = img.height * 0.5;
            cc2.drawImage(img, 0, 0, canvas2.width, canvas2.height);
            cc.drawImage(canvas2, 0, 0, canvas2.width * 0.5, canvas2.height * 0.5,
                0, 0, canvas.width, canvas.height);

            canvas.toBlob(function(blob) {
                browser.downloads.download({
                    url : URL.createObjectURL(blob),
                    filename: 'file.jpg'
                });
                document.body.removeChild(canvas);
            }, 'image/jpeg');
        };
        img.src = info.srcUrl;
    }
});

的manifest.json:

{
  "manifest_version": 2,
  "name": "ImageResizeDownload",
  "description": "Downloads image in different sizes.",
  "version": "1.0",

  "background": {
    "scripts": ["image-resize-download.js"]
  },

  "permissions": [
    "menus",
    "downloads"
  ]
}

问题是后台脚本似乎无法创建画布的blob而是崩溃。我已经尝试应用包含脚本作为背景页面的html页面,这也没有用。当我在内容脚本中实现侦听器函数时,blob函数工作正常,但脚本缺少API的必要权限。

有没有办法让后台脚本提示下载画布内容?或者我是否必须使用与后台通信的其他内容脚本?

1 个答案:

答案 0 :(得分:0)

尝试将"<all_urls>" permission添加到您的manifest.json

当我尝试在Firefox扩展中使用canvas时,我收到了DOM安全性错误。添加该权限可以解决我的问题。我在阅读了bug report之后试了一下,有人提到"<all_urls>"