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
html css js url shortener cachestorage "#/"
Sure! Here’s a simple example of a URL shortener implemented with HTML, CSS, and JavaScript that uses the Cache Storage API to persist the shortened URLs client-side. It also leverages # in the URL to handle routing of shortened URLs.
{ shortCode: originalURL } in Cache Storageyourdomain.com/#/abc12yourdomain.com/#/abc12, the script looks up the original URL and redirects there<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Simple URL Shortener 📝</title>
<style>
body {
font-family: Arial, sans-serif;
max-width: 500px;
margin: 3rem auto;
padding: 1rem;
background: #f9fafb;
color: #333;
}
h1 {
text-align: center;
margin-bottom: 1.5rem;
}
label, input, button {
display: block;
width: 100%;
margin-bottom: 1rem;
}
input {
padding: 0.5rem;
font-size: 1.125rem;
}
button {
padding: 0.75rem;
font-size: 1.125rem;
background: #007bff;
color: white;
border: none;
cursor: pointer;
}
button:hover {
background: #0056b3;
}
#result {
margin-top: 1rem;
padding: 0.5rem;
background: #e8f0fe;
border: 1px solid #c6d9fc;
word-break: break-all;
}
a.short-url {
color: #007bff;
text-decoration: none;
}
a.short-url:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<h1>Simple URL Shortener</h1>
<label for="url-input">Enter URL to shorten:</label>
<input type="url" id="url-input" placeholder="https://example.com" required />
<button id="shorten-btn">Shorten URL</button>
<div id="result"></div>
<script>
// Cache Storage key for storing mappings
const CACHE_NAME = 'url-shortener-cache-v1';
const urlInput = document.getElementById('url-input');
const shortenBtn = document.getElementById('shorten-btn');
const resultDiv = document.getElementById('result');
// Generate a random short code (5 chars)
function generateShortCode() {
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let code = '';
for(let i=0; i<5; i++) {
code += chars.charAt(Math.floor(Math.random() * chars.length));
}
return code;
}
// Load stored shortcodes from the Cache Storage
async function loadMappings() {
if (!('caches' in window)) return {};
const cache = await caches.open(CACHE_NAME);
const requests = await cache.keys();
// Map of shortCode -> URL
const mappings = {};
for (const request of requests) {
const response = await cache.match(request);
if (response) {
const url = await response.text();
// request.url = e.g. http://example.com/abc12
const shortCode = new URL(request.url).pathname.slice(1);
mappings[shortCode] = url;
}
}
return mappings;
}
// Save a new shortCode -> URL mapping in Cache Storage
async function saveMapping(shortCode, url) {
if (!('caches' in window)) return;
const cache = await caches.open(CACHE_NAME);
// We use the request url pathname as the key for cache
const request = new Request(location.origin + '/' + shortCode);
const response = new Response(url, {
headers: { 'Content-Type': 'text/plain' }
});
await cache.put(request, response);
}
// Main shorten button handler
shortenBtn.addEventListener('click', async () => {
const originalUrl = urlInput.value.trim();
if (!originalUrl) {
alert('Please enter a valid URL');
return;
}
// Basic URL validation
let urlParsed;
try {
urlParsed = new URL(originalUrl);
} catch {
alert('Invalid URL');
return;
}
// Load existing mappings to prevent collisions
const mappings = await loadMappings();
// Generate unique short code
let shortCode;
do {
shortCode = generateShortCode();
} while (mappings[shortCode] !== undefined);
// Save mapping
await saveMapping(shortCode, originalUrl);
// Show shortened URL
const shortUrl = location.origin + '/#/' + shortCode;
resultDiv.innerHTML = `Shortened URL: <a class="short-url" href="${shortUrl}" target="_blank" rel="noopener">${shortUrl}</a>`;
});
// Handle redirect if URL contains #/shortCode
async function handleRedirect() {
const hash = location.hash;
if (hash.startsWith('#/')) {
const shortCode = hash.slice(2);
const mappings = await loadMappings();
if (mappings[shortCode]) {
window.location.href = mappings[shortCode];
} else {
resultDiv.textContent = 'Short URL not found in cache.';
}
}
}
// On page load check for hash redirect
window.addEventListener('load', handleRedirect);
// Also handle hashchange events (in case user changes the hash manually)
window.addEventListener('hashchange', handleRedirect);
</script>
</body>
</html>
/#/abc12If you want me to help turn this into a PWA with service workers, or handle longer codes, just ask!
Not yet included in a published release.