Description
+ Random download image button
+ Click button >> Download an image
+ Get images from a gallery image in Not Linked Page
#1. Add a Page in Not Linked with:
+ Name: any name what you want
+ URL: /random-images-gallery
#2. Next, add a Gallery Grid Section to Not Linked Page
#3. Edit page where you want to place Download button > Add a Code Block > Paste this code.
<div id="random-download">
<button id="download-btn">Get Random Image</button>
<div id="loading" style="display: none;">Loading images...</div>
</div>
<style>
button#download-btn {
background-color: #000 !important;
color: #fff !important;
padding: 10px 20px !important;
border-radius: 50px;
}
</style>
<script>
let galleryImages = [];
async function fetchGalleryImages() {
try {
const response = await fetch('/random-images-gallery');
const html = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
const imageElements = doc.querySelectorAll('.gallery-grid-item img[data-src]');
const images = [];
imageElements.forEach(img => {
const dataSrc = img.getAttribute('data-src');
if (dataSrc) {
images.push(dataSrc);
}
});
return images;
} catch (error) {
console.error('Error fetching gallery images:', error);
return [];
}
}
async function initializeGallery() {
const loadingEl = document.getElementById('loading');
const btnEl = document.getElementById('download-btn');
loadingEl.style.display = 'block';
btnEl.disabled = true;
galleryImages = await fetchGalleryImages();
loadingEl.style.display = 'none';
btnEl.disabled = false;
if (galleryImages.length === 0) {
btnEl.textContent = 'No Images Found';
btnEl.disabled = true;
}
}
document.getElementById('download-btn').addEventListener('click', async () => {
if (galleryImages.length === 0) {
alert('No images available. Please try refreshing the page.');
return;
}
const randomImage = galleryImages[Math.floor(Math.random() * galleryImages.length)];
try {
const resp = await fetch(randomImage, { mode: 'cors' });
if (!resp.ok) throw new Error('Network response was not ok');
const blob = await resp.blob();
const blobUrl = URL.createObjectURL(blob);
const link = document.createElement('a');
link.style.display = 'none';
link.href = blobUrl;
try {
link.download = (new URL(randomImage)).pathname.split('/').pop() || 'gallery-image';
} catch (e) {
link.download = 'gallery-image';
}
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
setTimeout(() => URL.revokeObjectURL(blobUrl), 1500);
} catch (err) {
console.warn('Could not fetch blob for download, opening in new tab as fallback:', err);
window.open(randomImage, '_blank', 'noopener');
}
});
initializeGallery();
</script>



