Load packaged assets (images) into array

Hi, I am working on my first addon. Its essentially just a glorified homepage/newtab page. I’ll be referring to the images dir going forward.

.
├── home-paper-style.png
├── ico
│   ├── dark.png
│   └── light.png
├── images
│   ├── black-swan-dark.jpg
│   ├── black-swan-light.jpg
│   ├── bladerunner-dark.jpg
│   ├── bladerunner_02-dark.jpg
│   ├── ex-machina-dark.jpg
│   ├── ex-machina-light.jpg
│   
├── manifest.json
├── script.js
├── startpage.html
├── styles
│   ├── Hack.ttf
│   ├── colors_lunar.css
│   ├── colors_paper.css
│   ├── style_lunar.css
│   └── style_paper.css
└── web-ext-artifacts
    └── home-1.0.zip

For now this is just a mini project to get familiar with js/html, this is my first time doing anything with it. I do not plan on publishing this unless it evolves into something generally useful.

Whenever a newtab is loaded I am injecting a random image from images/.

function getRandomImage() {
	var images = ["black-swan-dark.jpg","black-swan-light.jpg","suspiria-dark.jpg"];
	return images[Math.floor(Math.random() * images.length)];
} 

I plan on adding many more images and manually populating the array like above seems tedious. With nodejs I would just do something like:

var fs = require('fs');
var images = fs.readdirSync('images/');
return images[Math.floor(Math.random() * images.length)];

What would be the equivalent within the context of a webextension? Since these are packaged assets and not reading directly from the users filesystem I figure there has to be a way to read the images folder into an array.

I have read through the firefox webextension doc and examples but I am still a bit lost.

Any pointers would be very appreciated. Thanks for your time.

1 Like

I’m not sure it’s possible.
I had a similar problem and I’ve ended up simply naming the files “0.svg”, “1.svg”, “2.svg”… and then using random number to access random image.

But you still need to track number of images (or start by blindly looping through the files with “fetch” until you get “not found” error :slight_smile:, then you know how many images you have).

Alternatively, you can write a build script that will use “fs” to get the list the of files and then store it in some JSON file which can then be fetched by your extension.

1 Like

I had a similar problem and I’ve ended up simply naming the files “0.svg”, “1.svg”, “2.svg”… and then using random number to access random image.

Right on. I’ll probably take that approach also. Thanks for info.

1 Like