JavaScript Fetch API with Blob Handling
This example uses the Fetch API to retrieve the QR code as a Blob, then creates an Object URL to display it.
async function generateQR() {
const url = document.getElementById('urlInput').value;
const apiUrl = `https://qr.dee4u.com/api/qr?data=${encodeURIComponent(url)}&size=400`;
try {
// Show loading
document.getElementById('qrDisplay').innerHTML =
'<div class="loading">Generating...</div>';
// Fetch QR code as blob
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error('Failed to generate QR code');
}
const blob = await response.blob();
const objectUrl = URL.createObjectURL(blob);
// Display image
document.getElementById('qrDisplay').innerHTML =
`<img src="${objectUrl}" alt="QR Code">`;
// Store for download
window.currentQrBlob = blob;
document.getElementById('downloadBtn').style.display = 'block';
} catch (error) {
document.getElementById('qrDisplay').innerHTML =
`<div style="color: red;">Error: ${error.message}</div>`;
}
}
function downloadQR() {
if (window.currentQrBlob) {
const url = URL.createObjectURL(window.currentQrBlob);
const a = document.createElement('a');
a.href = url;
a.download = 'qrcode.png';
a.click();
URL.revokeObjectURL(url);
}
}
function generateQRSimple() {
const url = document.getElementById('urlInput').value;
const apiUrl = `https://qr.dee4u.com/api/qr?data=${encodeURIComponent(url)}&size=400`;
// Simply set as image source
document.getElementById('qrDisplay').innerHTML =
`<img src="${apiUrl}" alt="QR Code">`;
}