【发布时间】:2017-05-23 16:24:16
【问题描述】:
我正在开发一个 chrome 扩展。 现在扩展程序每小时调用一次 API 并获取图像。 我想将所述图像保存在 chrome.storage.local 中。
但是,图像非常大,所以我使用 canvas 压缩也就是调整图像大小。
这就是我尝试将 src(我从 API 调用中获得)注入图像的原因。我以为我可以注入到我的 background.html 中存在的图像标签中。
这是我的清单
{
"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"在后台页面声明中实际上构建了一个空的自动生成的 html 页面,因此您的 background.html 永远不会被使用。只需删除"scripts"并通过<script>标签包含 js 文件。 -
@wOxxOm 你的意思是完全删除我的 background.js 文件?即使扩展未打开,background.js 中的任务也应该发生。
-
诶???我的意思是
"scripts"在您的 manifest.json 中键入。 -
@wOxxOm 如果我不理解,我很抱歉。你的意思是像这样留下清单?
"background": { "./js/jquery-3.2.1.min.js", "hot-reload.js", "background.js" }, -
不,这将是无效的语法。检查背景页面的文档。我以为我已经解释得很清楚了,但显然我不擅长解释。
标签: javascript google-chrome google-chrome-extension