gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
html css js url shortener cachestorage
- User
html css js url shortener cachestorage
- Assistant
Creating a simple URL shortener using HTML, CSS, JavaScript, and CacheStorage (part of the Service Worker Cache API) is a bit unorthodox since CacheStorage is meant for caching network requests/responses, not general data storage. However, you can simulate a URL shortener caching URLs with CacheStorage.
Below is a basic example demonstrating how you might implement a client-side URL shortener that stores shortened URL mappings in CacheStorage. This example uses:
- HTML & CSS for the UI
- JavaScript with Service Worker and CacheStorage for storing & retrieving shortened URLs
How it works:
- User inputs a URL.
- The app generates a short random key.
- Saves the mapping
{ shortKey -> original URL }in CacheStorage by creating a response with that URL as body. - When the short URL is opened, the service worker intercepts the fetch, recognizes shortKey, and redirects to the original URL.
Full example:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>URL Shortener with CacheStorage</title> <style> body { font-family: sans-serif; max-width: 600px; margin: 2em auto; padding: 0 1em; } input[type=text] { width: 100%; padding: 0.5em; font-size: 1em; } button { padding: 0.6em 1em; font-size: 1em; margin-top: 0.5em; } #result { margin-top: 1em; word-break: break-all; } </style> </head> <body> <h1>Simple URL Shortener (CacheStorage)</h1> <form id="shortenerForm"> <input id="urlInput" type="text" placeholder="Enter a URL to shorten" required /> <button type="submit">Shorten</button> </form> <div id="result"></div> <script> // Register service worker for handling redirects if ('serviceWorker' in navigator) { navigator.serviceWorker.register('sw.js') .then(() => console.log('Service Worker registered')) .catch(console.error); } // Generate a short random key function generateShortKey(length = 6) { const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; let key = ''; for (let i = 0; i < length; i++) { key += chars[Math.floor(Math.random() * chars.length)]; } return key; } async function saveUrlMapping(shortKey, originalUrl) { if (!('caches' in window)) { alert('Cache API not supported'); return false; } const cache = await caches.open('url-shortener-cache'); // Save a Response with the original URL as text body for the `shortKey` // We'll request 'https://short.url/<shortKey>' to get this Response const response = new Response(originalUrl, { headers: { 'Content-Type': 'text/plain' } }); await cache.put(`https://short.url/${shortKey}`, response); return true; } async function formSubmitHandler(e) { e.preventDefault(); const urlInput = document.getElementById('urlInput'); const originalUrl = urlInput.value.trim(); if (!originalUrl) return; // Basic validation try { new URL(originalUrl); } catch { alert('Please enter a valid URL'); return; } const shortKey = generateShortKey(); const success = await saveUrlMapping(shortKey, originalUrl); if (success) { const shortUrl = `${location.origin}/?id=${shortKey}`; document.getElementById('result').innerHTML = ` <p>Short URL:</p> <a href="${shortUrl}" target="_blank" rel="noopener">${shortUrl}</a> <p>Try opening it in a new tab to see redirection handled by Service Worker.</p> `; urlInput.value = ''; } else { alert('Failed to save URL mapping'); } } document.getElementById('shortenerForm').addEventListener('submit', formSubmitHandler); </script> </body> </html>
Service Worker (sw.js)
const CACHE_NAME = 'url-shortener-cache'; self.addEventListener('install', event => { self.skipWaiting(); }); self.addEventListener('activate', event => { event.waitUntil(self.clients.claim()); }); // Intercept fetch and check if request is a short URL redirect self.addEventListener('fetch', event => { const url = new URL(event.request.url); // We only want to handle requests coming to our origin with path '/' and ?id=<shortKey> if (url.origin === self.origin && url.pathname === '/' && url.searchParams.has('id')) { const shortKey = url.searchParams.get('id'); event.respondWith( caches.open(CACHE_NAME).then(cache => cache.match(`https://short.url/${shortKey}`).then(response => { if (!response) { return new Response('Short URL not found', { status: 404, statusText: 'Not Found' }); } return response.text().then(originalUrl => { // Redirect to the original URL return Response.redirect(originalUrl, 302); }); }) ) ); } });
How to test:
- Save
index.htmlandsw.jsin the same folder. - Serve this folder with a local web server (Cache API requires https or localhost).
For example:
npx http-server -c-1orpython -m http.server - Open the page in your browser (localhost).
- Enter a full URL like
https://example.com, click Shorten. - You get a URL like
http://localhost:8080/?id=abc123. - Open that URL in a new tab, and the service worker intercepts and redirects to the original.
Notes:
- This is a client-only demonstration. No backend.
- CacheStorage is used here for simple persistent key-value pairs associating short keys with URLs.
- In production a URL shortener requires a backend and database for sharing URLs publicly.
- The CacheStorage API limits size; this is just a demo.
- The service worker redirect simulates URL shortening redirect on client side.
If you want a simpler storage without service workers, consider
localStorageorIndexedDBinstead.
Let me know if you want me to provide a version using localStorage/indexedDB or purely frontend logic!