gpt4 book ai didi

javascript - 如何将图像从background.js加载到background.html?

转载 作者:行者123 更新时间:2023-12-03 04:15:51 25 4
gpt4 key购买 nike

我正在开发一个 Chrome 扩展。现在,该扩展每小时进行一次 API 调用并获取图像。我想将所述图像保存在 chrome.storage.local 中。

但是,图像相当大,因此我使用 Canvas 压缩(即调整图像大小)。

这就是为什么我尝试将 src(我从 API 调用中获得)注入(inject)到图像中。我认为我能够注入(inject)到我的background.html 中存在的图像标签中。

这是我的 list

{
"manifest_version": 2,
"name": "moodflow",
"short_name": "moodflow",
"description": "",
"version": "0.0.0.10",
"author": "Walter J. Monecke",
"chrome_url_overrides" : {
"newtab": "index.html"
},
"background": {
"scripts": ["./js/jquery-3.2.1.min.js", "hot-reload.js", "background.js"],
"pages": ["background.html"]
},
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
"permissions": [
"storage",
"alarms",
"unlimitedStorage",
"activeTab",
"https://www.youtube.com/iframe_api",
"https://api.unsplash.com/photos/random",
"https://api.unsplash.com/photos/random/*"
]
}

这是我在 background.js 中的 jQuery AJAX:

$.ajax({
url: "https://api.unsplash.com/photos/random",
type: 'get',
async: true,
dataType: "json",
data: "client_id=29b43b6caaf7bde2a85ef2cfddfeaf1c1e920133c058394a7f8dad675b99921b&collections=281002",
success: (response) => {
alert('successful API');
alert(response);
// insert src into img
$('#source_img').css('display', 'none');


$('#source_img').on('load', function() {
alert('Image has loaded!');
//compressImageAndSave();
}).attr('src', response.urls.raw);
},
error: () => {
alert('getPictureApi AJAX failed');
}
});

这是我的background.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<img src="" id="source_img">
</body>
</html>

我认为我的错误是我假设我的background.js可以与我的background.html交互。

我做错了什么?

最佳答案

只能有一个背景页面。当前您尝试声明两个后台页面:"scripts"创建一个自动生成的空页面和 "pages"是正常背景页面的无效声明。

删除"scripts"部分,通过 <script> 链接 js 文件html 中的标签,请使用正确的 "page"具有单个值的声明。

ma​​nifest.json

{
"manifest_version": 2,
"name": "moodflow",
"short_name": "moodflow",
"description": "",
"version": "0.0.0.10",
"author": "Walter J. Monecke",
"chrome_url_overrides" : {
"newtab": "index.html"
},
"background": {
"page": "background.html"
},
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'",
"permissions": [
"storage",
"alarms",
"unlimitedStorage",
"activeTab",
"https://www.youtube.com/iframe_api",
"https://api.unsplash.com/photos/random",
"https://api.unsplash.com/photos/random/*"
]
}

背景.html

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<img src="" id="source_img">
<script src="./js/jquery-3.2.1.min.js"></script>
<script src="hot-reload.js"></script>
<script src="background.js"></script>
</body>
</html>

background.js不变。

关于javascript - 如何将图像从background.js加载到background.html?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44140262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com