Skip to content

Commit

Permalink
Display decoded SVGs on page
Browse files Browse the repository at this point in the history
  • Loading branch information
simonw authored Oct 26, 2024
1 parent 7058388 commit a7289c8
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions svg-sandbox.html
Original file line number Diff line number Diff line change
Expand Up @@ -59,5 +59,67 @@ <h2>SVG with JavaScript (ignored)</h2>
<footer>
<p>Note: When SVGs are embedded using <code>img</code> tags with base64 data URIs, any JavaScript or interactive elements are safely ignored by the browser.</p>
</footer>

<script>
// 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
const pre = document.createElement('pre');
pre.style['white-space'] = 'pre-wrap';
pre.innerText = svgContent.replace(/>/g,'>\n');
container.appendChild(pre);

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';

// 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);
}
}
});
document.body.appendChild(decodedContainer);
}

// Run the script
displayDecodedSVGs();
</script>
</body>
</html>

0 comments on commit a7289c8

Please sign in to comment.