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

时间:2017-05-23 16:24:16

标签: javascript google-chrome google-chrome-extension

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

然而,图像非常大,所以我正在压缩使用画布来调整图像大小。

这就是我试图将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进行交互。

我做错了什么?

1 个答案:

答案 0 :(得分:1)

只能有一个背景页面。 目前,您尝试声明两个背景页面:"scripts"创建自动生成的空白页面,"pages"是普通背景页面的无效声明。

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

<强>的manifest.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/*"
  ]
}

<强> background.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 不变。