gpt-4.1-mini-2025-04-14· OpenAI WildChat-4.8M (AI2)
html css js url shortener sharedStorage "#/"
- User
html css js url shortener sharedStorage "#/"
- Assistant
Certainly! Below is a simple example of a URL shortener implemented in plain HTML, CSS, and JavaScript. It uses the browser’s
SharedStorageAPI to save and retrieve URL mappings. The shortened URLs use the#/<key>fragment identifier format for routing.
Features:
- Input a long URL and get a short URL with the format
yourdomain/#/<shortKey> - Clicking the short URL or visiting with
#/<shortKey>in URL redirects to the original URL. - URLs and keys are saved in SharedStorage (if supported).
- Basic validation and short key generation.
Important:
- The
SharedStorageAPI is a very new web platform feature and is not widely supported in all browsers yet (mostly experimental or behind flags). - Fallback is localStorage for wider compatibility.
- This is a demo implementation, not suitable for production use.
Complete code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>URL Shortener with SharedStorage</title> <style> body { font-family: Arial, sans-serif; max-width: 600px; margin: 40px auto; padding: 0 16px; } h1 { text-align: center; } label, input, button { display: block; width: 100%; } label { margin-bottom: 6px; font-weight: bold; } input[type="url"] { font-size: 1rem; padding: 8px; margin-bottom: 12px; } button { padding: 10px; font-size: 1rem; } #result { margin-top: 20px; word-break: break-all; } #error { color: red; } </style> </head> <body> <h1>URL Shortener</h1> <label for="urlInput">Enter URL to shorten:</label> <input id="urlInput" type="url" placeholder="https://example.com" required /> <button id="shortenBtn">Shorten URL</button> <div id="result"></div> <div id="error"></div> <script> (function(){ const urlInput = document.getElementById('urlInput'); const shortenBtn = document.getElementById('shortenBtn'); const result = document.getElementById('result'); const error = document.getElementById('error'); // Use SharedStorage if available, else fallback localStorage const storageAPI = { async getItem(key) { if ('sharedStorage' in navigator) { try { return await navigator.sharedStorage.get(key); } catch { // fallback? } } // fallback to localStorage synchronously return Promise.resolve(localStorage.getItem(key)); }, async setItem(key, value) { if ('sharedStorage' in navigator) { try { await navigator.sharedStorage.set(key, value); return; } catch(e) { // fallback below } } localStorage.setItem(key, value); } }; // Generate random alphanumeric key of length 6 function generateKey(length = 6) { const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; let key = ''; for(let i=0; i<length; i++) { key += chars.charAt(Math.floor(Math.random() * chars.length)); } return key; } // Validate URL format function isValidUrl(url) { try { new URL(url); return true; } catch { return false; } } // Create short URL async function createShortUrl(longUrl) { // Check if url is already saved, and return existing key // Scan storage (not efficient but demo) // We'll cache keys in localStorage for quick listing of keys // Try keys from storage: // We store key => longUrl // To check if longUrl exists, scan all keys (not scalable. Demo only!) // Note: SharedStorage API does not provide keys method yet, // We'll rely only on localStorage keys here as fallback. // Check in localStorage keys only for now for(let i=0; i<localStorage.length; i++) { const k = localStorage.key(i); const val = localStorage.getItem(k); if(val === longUrl){ return k; } } // Generate unique key let key = generateKey(); while (await storageAPI.getItem(key) !== null) { key = generateKey(); } await storageAPI.setItem(key, longUrl); return key; } shortenBtn.addEventListener('click', async () => { error.textContent = ''; result.textContent = ''; const inputUrl = urlInput.value.trim(); if (!inputUrl) { error.textContent = 'Please enter a URL.'; return; } if (!isValidUrl(inputUrl)) { error.textContent = 'Invalid URL format.'; return; } shortenBtn.disabled = true; shortenBtn.textContent = 'Shortening...'; try { const key = await createShortUrl(inputUrl); const shortUrl = location.origin + '/#/' + key; result.innerHTML = `Short URL: <a href="${shortUrl}" target="_blank">${shortUrl}</a>`; } catch (e) { error.textContent = 'Error shortening URL: ' + e.message; } finally { shortenBtn.disabled = false; shortenBtn.textContent = 'Shorten URL'; } }); // On page load, check location.hash and redirect if needed async function handleRedirect() { if(location.hash.startsWith('#/')) { const key = location.hash.slice(2); if (!key) return; result.textContent = 'Resolving short URL...'; let longUrl = await storageAPI.getItem(key); if(longUrl) { // Clear UI before redirecting result.textContent = `Redirecting to: ${longUrl}`; window.location.href = longUrl; } else { error.textContent = 'Short URL not found.'; result.textContent = ''; } } } // On load handleRedirect(); })(); </script> </body> </html>
How it works:
- Enter a long URL and click Shorten URL.
- A random 6-character key is generated and stored with the long URL.
- The short URL is shown as
yourdomain/#/<key> - When you visit this short URL (including on page load with such a hash), the script reads the key from the
location.hashand redirects the browser to the saved long URL. - Storage uses
navigator.sharedStorageif available, otherwise fallback tolocalStorage.
Testing locally:
- Due to CORS and certain API restrictions, open the file via a local HTTP server rather than directly as file://.
- You can use
npx http-serverorpython3 -m http.serverto test.
Let me know if you'd like enhancements like analytics, custom aliases, or more robust storage!
- Input a long URL and get a short URL with the format
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.