2017-05-23 50 views
0

我正在開發一個Chrome擴展。 現在,擴展程序正在每小時進行一次API調用並獲取圖像。 我想將所述圖像保存在chrome.storage.local中。如何將圖像從background.js加載到background.html?

但是,圖像非常大,所以我正在使用畫布壓縮又名圖像大小。

這就是爲什麼我試圖將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/*" 
    ] 
} 

,這是我的jQuery AJAX在background.js

$.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> 

我認爲我的錯誤是tha我假設我的background.js可以與我的background.html進行交互。

我在做什麼錯?

+0

背景頁面聲明中的腳本實際上會生成一個空的自動生成的html頁面,因此您的background.html從不會被使用。只需刪除''腳本''並通過'

相關問題