首页 > 解决方案 > 如何使用浏览器扩展将上传的图像放到 html 画布上?

问题描述

我以前从未使用过 javascript 或 html,我正在尝试制作一个浏览器扩展,将图像放在 html 画布上。一切都使用我电脑中的图像,但我想不出一种方法来允许使用扩展的其他人使用他们自己的图像。我找不到任何 javascript 命令供用户选择文件。html 有很多教程,但似乎我只能在扩展弹出窗口中使用 html,而且我不知道如何将该图像发送到内容脚本。当我尝试该方法时,它会输出错误,

Content Security Policy: The page’s settings blocked the loading of a resource at inline (“script-src”).

我在这里看到了其他关于在顶部添加一些内容的帖子,例如,

<meta http-equiv="Content-Security-Policy" content="default-src *;...

但这并没有改变任何东西。如果有一些文件夹就好了,我可以告诉用户将他们的图像复制到那里然后重命名它,但是我找不到任何用于浏览器扩展的文件夹。如果这很重要,我正在使用 Firefox。我能想到的最后一个选择是以某种方式集成 github 并让用户在那里上传图像,但我还没有研究过。有没有更简单的方法来做到这一点?

我的代码:

清单.json

{
    "manifest_version": 2,
    "name": "Pixel Canvas Template",
    "version": "0.1",
    "content_scripts": [{
        "matches": [ "https://pixelcanvas.io/*" ],
        "js": [ "content.js" ]
    }],
    "applications": {
        "gecko": {
            "id": "PixelCanvasTemplate@google.com"
        }
    },
    "background": {
        "scripts": ["background.js"]
    },
    "browser_action": {
        "default_icon": "PCLogo.png",
        "default_popup": "popup.html"
    },
    "permissions": [ 
        "webRequest",
        "webRequestBlocking",
        "https://pixelcanvas.io/*",
        "https://europe-west1-pixelcanvasv2.cloudfunctions.net/pixel",
        "tabs"
    ]
}

popup.html

<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval' http://www.google.com">
<html>
<body>
    <p><input type="file"  accept="image/*" name="image" id="file" onchange="loadFile(event)" style="display: none;"></p>
    <p><label for="file" style="cursor: pointer;">Upload Image</label></p>
    <script>
        var loadFile = function(event) {
            chrome.tabs.query({active: true, lastFocusedWindow: true}, tabs => {
                chrome.tabs.sendMessage(tabs[0].id, {url: URL.createObjectURL(event.target.files[0])});
            });
        };
    </script>
</body>
</html>

内容.js

browser.runtime.onMessage.addListener(upload);
var img = new Image();
var width = 0;
var height = 0;
img.onload = function() {
  width = this.width;
  height = this.height;
}
img.src = chrome.extension.getURL('ServerLink.png');

function upload(message) {
  console.log(message);
  img.src = message.url;
}

function animate() {
  //display image
}
animate();

标签: javascripthtmlfirefox-addon

解决方案


推荐阅读