human (Oct 26, 2024, 01:41 PM)
Write JavaScript which scans the existing HTML for images with base64 svg in their src= attribute and then outputs the decoded SVG for each one at the bottom of the page, using the alt attribute of the image as a h3 title
assistant (Oct 26, 2024, 01:41 PM)
I'll help you create JavaScript code that finds images with base64 SVG content and displays the decoded SVGs.
// Function to decode base64 to string
function decodeBase64(str) {
// Remove data URL prefix if present
const base64Data = str.replace(/^data:image\/svg\+xml;base64,/, '');
try {
return atob(base64Data);
} catch (e) {
console.error('Error decoding base64:', e);
return null;
}
}
// Function to create and append SVG section
function appendSVG(title, svgContent) {
const container = document.createElement('div');
container.style.marginTop = '20px';
container.style.padding = '10px';
container.style.border = '1px solid #ccc';
// Add title
const heading = document.createElement('h3');
heading.textContent = title;
container.appendChild(heading);
// Add SVG content
container.innerHTML += svgContent;
return container;
}
// Main function to process images and display SVGs
function displayDecodedSVGs() {
// Create container for decoded SVGs
const decodedContainer = document.createElement('div');
decodedContainer.id = 'decoded-svgs';
const containerTitle = document.createElement('h2');
containerTitle.textContent = 'Decoded SVGs';
decodedContainer.appendChild(containerTitle);
// Find all images
const images = document.querySelectorAll('img');
let svgCount = 0;
images.forEach(img => {
const src = img.getAttribute('src');
if (src && src.startsWith('data:image/svg+xml;base64,')) {
const decodedSVG = decodeBase64(src);
if (decodedSVG) {
const title = img.getAttribute('alt') || `SVG ${++svgCount}`;
const svgContainer = appendSVG(title, decodedSVG);
decodedContainer.appendChild(svgContainer);
}
}
});
// Only append container if we found SVGs
if (svgCount > 0) {
document.body.appendChild(decodedContainer);
} else {
console.log('No base64 encoded SVGs found in the document.');
}
}
// Run the script
displayDecodedSVGs();
This script will:
- Find all
<img>
elements in the document - Check if their
src
attribute contains base64-encoded SVG data - Decode the base64 data to get the original SVG markup
- Create a new section at the bottom of the page with each decoded SVG
- Use the image's
alt
attribute as the title (or generate a numbered title if no alt text exists)
Each decoded SVG will be displayed in its own container with a title above it. The script handles errors gracefully and will only create the decoded section if it actually finds base64-encoded SVGs.
To use this script, you can either:
- Add it to your HTML file inside a
<script>
tag - Save it as a separate .js file and include it in your HTML
- Run it in the browser's developer console
Would you like me to explain any part of the code in more detail or help you adapt it for a specific use case?