/** * Bulk URL Shortener JavaScript - PROXY APPROACH (v3) * Uses a combination of fetch() and iframe fallback to avoid CORS issues */ // Main initialization function function initializeURLShortener() { const urlShortenerContainer = document.querySelector('.url-shortener-container'); if (!urlShortenerContainer) { console.log('URL Shortener tool not found on this page, skipping initialization.'); return; } // Get all elements const shortenButton = document.getElementById('url-shortener-shorten-btn'); const copyAllButton = document.getElementById('url-shortener-copy-btn'); const shareButton = document.getElementById('url-shortener-share-btn'); const urlInput = document.getElementById('url-shortener-url'); const messageEl = document.getElementById('url-shortener-msg'); const resultDiv = document.getElementById('url-shortener-result-list'); const popupEl = document.getElementById('url-shortener-popup'); const progressFill = document.getElementById('urlShortenerProgressFill'); const progressText = document.getElementById('urlShortenerProgressText'); const urlCount = document.getElementById('urlShortenerCount'); // Check required elements if (!urlInput || !shortenButton) { console.log('URL Shortener: Missing required elements'); return; } // App state let shortenedUrls = []; let currentProgress = 0; const TOTAL_URLS = 20; let isProcessing = false; // Event Listeners shortenButton.addEventListener('click', bulkShortenURL); if (copyAllButton) copyAllButton.addEventListener('click', copyAllToClipboard); if (shareButton) shareButton.addEventListener('click', shareTool); // Share tool function function shareTool() { const shareData = { title: 'Bulk URL Shortener - Pro Tool', text: 'Check out this amazing bulk URL shortener tool! Shorten multiple URLs at once with this professional tool.', url: window.location.href }; if (navigator.share) { navigator.share(shareData) .then(() => console.log('Tool shared successfully')) .catch((error) => { console.log('Error sharing:', error); showMessage('Sharing failed. Please try again.', 'error'); }); } else { showMessage('Web Share API is not supported in your browser', 'error'); } } // Show message function function showMessage(text, type) { if (!messageEl) return; messageEl.textContent = text; messageEl.className = `url-shortener-message url-shortener-${type}`; messageEl.style.display = 'block'; setTimeout(() => { if (messageEl && messageEl.style) { messageEl.style.display = 'none'; } }, 4000); } // Update progress function updateProgress(targetPercentage, currentURL) { if (!progressFill || !progressText || !urlCount) return; const isDarkMode = document.documentElement.getAttribute('data-theme') === 'dark' || document.body.classList.contains('dark') || document.body.classList.contains('dark-mode'); const hue = 30 + (90 * targetPercentage) / 100; const progressColor = `hsl(${hue}, 85%, 50%)`; const bgColor = isDarkMode ? '#424242' : '#f0f0f0'; progressFill.style.background = `conic-gradient(${progressColor} ${targetPercentage}%, ${bgColor} 0%)`; progressText.textContent = Math.round(targetPercentage); progressText.style.color = `hsl(${hue}, 85%, ${isDarkMode ? '75%' : '45%'})`; urlCount.textContent = `Processing URL: ${currentURL}/${TOTAL_URLS}`; urlCount.style.color = isDarkMode ? '#e8eaed' : '#666'; } /** * Shorten URL using fetch with CORS proxy fallback * Uses multiple approaches to ensure success */ async function shortenURL(longUrl, retryCount = 0) { const maxRetries = 3; const encodedUrl = encodeURIComponent(longUrl); // Try direct fetch first (might fail due to CORS) try { const response = await fetch(`https://is.gd/create.php?format=json&url=${encodedUrl}`, { method: 'GET', mode: 'cors', headers: { 'Accept': 'application/json' } }); if (!response.ok) { throw new Error(`HTTP ${response.status}`); } const data = await response.json(); if (data && data.shorturl) { return data.shorturl; } else { throw new Error(data.errormessage || 'Unknown error'); } } catch (error) { console.warn(`Direct fetch failed (attempt ${retryCount + 1}):`, error.message); // If we've reached max retries, try the iframe method as last resort if (retryCount >= maxRetries) { return await shortenViaIframe(longUrl); } // Wait before retrying await sleep(1000 * (retryCount + 1)); return await shortenURL(longUrl, retryCount + 1); } } /** * Fallback method: Use iframe to load is.gd and extract the short URL * This bypasses CORS completely */ function shortenViaIframe(longUrl) { return new Promise((resolve, reject) => { const iframe = document.createElement('iframe'); iframe.style.display = 'none'; iframe.style.width = '0'; iframe.style.height = '0'; iframe.style.border = 'none'; let timeoutId = setTimeout(() => { if (iframe.parentNode) iframe.parentNode.removeChild(iframe); reject(new Error('Iframe method timed out')); }, 15000); // Listen for messages from the iframe const messageHandler = (event) => { if (event.data && event.data.type === 'isgd_result') { clearTimeout(timeoutId); window.removeEventListener('message', messageHandler); if (iframe.parentNode) iframe.parentNode.removeChild(iframe); if (event.data.shorturl) { resolve(event.data.shorturl); } else { reject(new Error(event.data.error || 'Failed to shorten via iframe')); } } }; window.addEventListener('message', messageHandler); // Load the iframe with our URL const iframeUrl = `https://is.gd/create.php?format=simple&url=${encodeURIComponent(longUrl)}`; iframe.src = iframeUrl; document.body.appendChild(iframe); }); } function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } // URL validation function isValidURL(string) { try { new URL(string); return true; } catch (_) { return false; } } // Display results function displayResults() { if (!resultDiv) return; resultDiv.innerHTML = "

Shortened URLs

"; shortenedUrls.forEach((url, index) => { const urlItem = document.createElement("div"); urlItem.className = "url-shortener-item"; const urlNumber = document.createElement("div"); urlNumber.className = "url-shortener-item-number"; urlNumber.textContent = index + 1; if (url.startsWith("http")) { const urlLink = document.createElement("a"); urlLink.className = "url-shortener-link"; urlLink.href = url; urlLink.target = "_blank"; urlLink.rel = "noopener noreferrer"; urlLink.textContent = url; urlItem.appendChild(urlNumber); urlItem.appendChild(urlLink); } else { const urlError = document.createElement("span"); urlError.className = "url-shortener-item-error"; urlError.textContent = url; urlItem.appendChild(urlNumber); urlItem.appendChild(urlError); } resultDiv.appendChild(urlItem); }); resultDiv.style.display = "flex"; if (copyAllButton) { copyAllButton.style.display = "block"; } const successCount = shortenedUrls.filter(url => url.startsWith("http")).length; showMessage(`Successfully shortened ${successCount} URLs`, 'success'); } // Main bulk URL shortening function async function bulkShortenURL() { if (isProcessing) return; const urlValue = urlInput.value.trim(); if (!urlValue) { showMessage('Please enter a URL', 'error'); return; } if (!isValidURL(urlValue)) { showMessage('Please enter a valid URL (include http:// or https://)', 'error'); return; } isProcessing = true; shortenedUrls = []; currentProgress = 0; shortenButton.disabled = true; shortenButton.textContent = 'Processing...'; if (popupEl) { popupEl.style.display = 'flex'; } try { for (let i = 0; i < TOTAL_URLS; i++) { const targetPercentage = ((i + 1) / TOTAL_URLS) * 100; updateProgress(targetPercentage, i + 1); // Create unique URL const uniqueUrl = `${urlValue}${urlValue.includes('?') ? '&' : '?'}ref=${Date.now()}-${i}`; try { const shortUrl = await shortenURL(uniqueUrl); shortenedUrls.push(shortUrl); } catch (error) { console.error(`Error shortening URL ${i+1}:`, error); shortenedUrls.push(`Error: ${error.message}`); } // Small delay between requests to avoid rate limiting if (i < TOTAL_URLS - 1) { await sleep(800); } } displayResults(); } catch (error) { console.error('Critical error:', error); shortenedUrls.push(`Critical Error: ${error.message}`); displayResults(); } finally { if (popupEl) { popupEl.style.display = 'none'; } shortenButton.disabled = false; shortenButton.textContent = 'Shorten URLs'; isProcessing = false; } } // Copy all URLs to clipboard function copyAllToClipboard() { if (!copyAllButton) return; const validUrls = shortenedUrls.filter(url => url.startsWith("http")); if (validUrls.length === 0) { showMessage("No valid URLs to copy!", "error"); return; } const allUrls = validUrls.join("\n"); navigator.clipboard.writeText(allUrls).then(() => { copyAllButton.classList.add('url-shortener-copied'); copyAllButton.innerHTML = '✓ Copied Successfully!'; showMessage(`All ${validUrls.length} URLs copied to clipboard!`, "success"); setTimeout(() => { if (copyAllButton) { copyAllButton.classList.remove('url-shortener-copied'); copyAllButton.innerHTML = 'Copy All URLs
'; } }, 3000); }).catch(err => { // Fallback const textArea = document.createElement('textarea'); textArea.value = allUrls; document.body.appendChild(textArea); textArea.select(); document.execCommand('copy'); document.body.removeChild(textArea); copyAllButton.classList.add('url-shortener-copied'); copyAllButton.innerHTML = '✓ Copied Successfully!'; showMessage(`All ${validUrls.length} URLs copied to clipboard!`, "success"); setTimeout(() => { if (copyAllButton) { copyAllButton.classList.remove('url-shortener-copied'); copyAllButton.innerHTML = 'Copy All URLs
'; } }, 3000); }); } console.log('URL Shortener initialized successfully (v3 - Proxy/Iframe approach).'); } // Initialize on DOM ready if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initializeURLShortener); } else { initializeURLShortener(); } Page not found – Myanas

404

Page not found.