Skip to content

Commit a7289c8

Browse files
authored
Display decoded SVGs on page
Some help from https://gist.github.com/simonw/e07899a173ffe9f5723994e1405f909a
1 parent 7058388 commit a7289c8

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

svg-sandbox.html

+62
Original file line numberDiff line numberDiff line change
@@ -59,5 +59,67 @@ <h2>SVG with JavaScript (ignored)</h2>
5959
<footer>
6060
<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>
6161
</footer>
62+
63+
<script>
64+
// Function to decode base64 to string
65+
function decodeBase64(str) {
66+
// Remove data URL prefix if present
67+
const base64Data = str.replace(/^data:image\/svg\+xml;base64,/, '');
68+
try {
69+
return atob(base64Data);
70+
} catch (e) {
71+
console.error('Error decoding base64:', e);
72+
return null;
73+
}
74+
}
75+
76+
// Function to create and append SVG section
77+
function appendSVG(title, svgContent) {
78+
const container = document.createElement('div');
79+
container.style.marginTop = '20px';
80+
container.style.padding = '10px';
81+
container.style.border = '1px solid #ccc';
82+
83+
// Add title
84+
const heading = document.createElement('h3');
85+
heading.textContent = title;
86+
container.appendChild(heading);
87+
88+
// Add SVG content
89+
const pre = document.createElement('pre');
90+
pre.style['white-space'] = 'pre-wrap';
91+
pre.innerText = svgContent.replace(/>/g,'>\n');
92+
container.appendChild(pre);
93+
94+
return container;
95+
}
96+
97+
// Main function to process images and display SVGs
98+
function displayDecodedSVGs() {
99+
// Create container for decoded SVGs
100+
const decodedContainer = document.createElement('div');
101+
decodedContainer.id = 'decoded-svgs';
102+
103+
// Find all images
104+
const images = document.querySelectorAll('img');
105+
let svgCount = 0;
106+
107+
images.forEach(img => {
108+
const src = img.getAttribute('src');
109+
if (src && src.startsWith('data:image/svg+xml;base64,')) {
110+
const decodedSVG = decodeBase64(src);
111+
if (decodedSVG) {
112+
const title = img.getAttribute('alt') || `SVG ${++svgCount}`;
113+
const svgContainer = appendSVG(title, decodedSVG);
114+
decodedContainer.appendChild(svgContainer);
115+
}
116+
}
117+
});
118+
document.body.appendChild(decodedContainer);
119+
}
120+
121+
// Run the script
122+
displayDecodedSVGs();
123+
</script>
62124
</body>
63125
</html>

0 commit comments

Comments
 (0)