javascript - 如何使用浏览器扩展将上传的图像放到 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();
解决方案
推荐阅读
- javascript - 用鼠标滚轮打开的新标签没有 window.opener 对象
- docker - Docker 无法在 Windows Server 2019 上使用 LCOW 启动服务实用程序 VM
- python - 尚未定义类型的 Python 类型提示
- angular - Angular Mat-table Paginator 在排序工作时中断
- makefile - buildroot 包 .mk 文件中的高级选项连接
- android - 当您必须使用父活动引用时,如何使用“FragmentScenario”单独测试 Fragment
- javascript - React.StrictMode:useEffect 中的 SetState 函数在运行一次 effect 时运行多次
- docker - GKE 集群出口设置
- javascript - 在 JavaScript 中重复一个函数不起作用
- python - matplotlib 中二维图的轴平均值