I am trying to make a simple extension that creates an array that persists between pages and tabs and stores every image link with a specific class from the web page. When I click on the extension button a small html page generates the preview of each image that was stored in the array with a link to the anchor tag around it.
Hello, I am new to chrome extensions and I am trying to make a basic image stripper that throws all images with the matching class into an array from all tabs when each page is loaded. Here is my code.
manifest.json
{
"name": "Link Viewer",
"version": "1",
"manifest_version" : 2,
"browser_action" :
{
"default_popup" : "history.html",
"default_icon" : "icon.png"
},
"background" : {"scripts" : ["persistent.js"]},
"content_scripts" :
[
{
"matches" : ["http://*/*"],
"js" : ["injection.js"]
}
]
}
history.html
<h1>Image Viewer</h1>
<div id="list">
<!-- Show Listed Images Here -->
</div>
injection.js
// Executes every page load
var elements = document.getElementsByClassName("img");
var imageLinks = [];
for(var i = 0; i < elements.length; i++)
{
imageLinks.push(elements[i].firstChild.src);
}
chrome.extension.sendRequest(imageLinks);
persistent.js
// This script gets run once when the browser is started
// Declare Persistent Image Array
var gifArray = [];
// Create an event listener for when requests are returned from the injection script
chrome.extension.onRequest.addListener
(
function(linksReturned)
{
// Loop through each returned link
for(var i = 0; i < linksReturned.length; i++)
{
var exists = false;
// loop through each link in the array and make sure it doesn't exist
for(var x = 0; x < gifArray.length; x++)
{
if(gifArray[x] == linksReturned[i])
{
gifArray.splice(x,1); // Remove that index from the array
exists = true;
break;
}
}
if(exists == false)
{
gifArray.push(linksReturned[i]);
}
}
// Links are stored and ready to be displayed on web page
}
);
// Popup HTML page when someone clicks on HTML button
window.onload = function()
{
var div = document.getElementById("list");
// Loop through each GIF and add to the list
for(var i = 0; i < gifArray.length; i++)
{
// Create the anchor element
var a = document.createElement("a");
// Create the image element
var img = document.createElement("img");
img.setAttribute("src",gifArray[i]);
// Put the image inside of the anchor
a.appendChild(img);
// Put the anchor inside the div
div.appendChild(a);
}
}
What am I doing wrong? How can I have a global list of every image with the class img indexed?