gpt-4.1-mini-2025-04-14· OpenAI
WildChat-4.8M (AI2)
html css js url shortener onstorage "#/"
- User
html css js url shortener onstorage "#/"
- Assistant
html css js url shortener onstorage "#/"
Creating a simple URL shortener using HTML, CSS, and JavaScript that uses localStorage and handles routing with hash /#/ can be done. The app will store shortened URLs in localStorage, allow the user to add new URLs, and navigate via hash routing.
Below is a complete example:
localStorage./#/abc123), redirects user to the original URL if found.<!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;
margin: 2rem;
background: #f8f9fa;
}
.container {
max-width: 500px;
margin: 0 auto;
background: white;
border-radius: 5px;
padding: 1.5rem;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}
h1 {
text-align: center;
margin-bottom: 1.5rem;
color: #333;
}
input[type=text] {
width: 100%;
padding: 0.75rem;
margin-bottom: 1rem;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 1rem;
}
button {
width: 100%;
padding: 0.75rem;
background-color: #007bff;
border: none;
border-radius:4px;
color: white;
font-size: 1rem;
cursor: pointer;
}
button:hover {
background-color: #0056b3;
}
.result {
margin-top: 1rem;
padding: 1rem;
background: #e9ecef;
border-radius: 4px;
word-break: break-all;
font-weight: bold;
color: #212529;
}
.error {
color: #dc3545;
margin-bottom: 1rem;
}
.footer {
margin-top: 3rem;
text-align: center;
font-size: 0.9rem;
color: #666;
}
a.short-url {
color: #007bff;
text-decoration: none;
}
a.short-url:hover {
text-decoration: underline;
}
</style>
</head>
<body>
<div class="container" id="app">
<!-- Content will be injected here -->
</div>
<script>
(function() {
const appDiv = document.getElementById('app');
const STORAGE_KEY = 'urlShortenerDB';
function loadDB() {
try {
const raw = localStorage.getItem(STORAGE_KEY);
return raw ? JSON.parse(raw) : {};
} catch(e) {
return {};
}
}
function saveDB(db) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(db));
}
// Generate a random 6-character string
function generateCode() {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let code = '';
for (let i = 0; i < 6; i++) {
code += chars.charAt(Math.floor(Math.random() * chars.length));
}
return code;
}
function validURL(str) {
try {
const url = new URL(str);
return url.protocol === "http:" || url.protocol === "https:";
} catch(e) {
return false;
}
}
// Render the home page (input form)
function renderHome() {
appDiv.innerHTML = `
<h1>Simple URL Shortener</h1>
<form id="shortenForm">
<input id="urlInput" type="text" placeholder="Enter long URL (http:// or https://)" required />
<div id="errorMsg" class="error" style="display:none;"></div>
<button type="submit">Shorten</button>
</form>
<div id="result" class="result" style="display:none;"></div>
<div class="footer">To retrieve your URL, visit <code>/#/yourcode</code></div>
`;
const form = document.getElementById('shortenForm');
const urlInput = document.getElementById('urlInput');
const errorMsg = document.getElementById('errorMsg');
const resultDiv = document.getElementById('result');
form.addEventListener('submit', (e)=>{
e.preventDefault();
errorMsg.style.display = 'none';
resultDiv.style.display = 'none';
const url = urlInput.value.trim();
if (!validURL(url)) {
errorMsg.textContent = 'Please enter a valid URL starting with http:// or https://';
errorMsg.style.display = 'block';
return;
}
let db = loadDB();
// Check if URL already exists in DB to avoid duplicates
for (let key in db) {
if (db[key] === url) {
// Found existing code
showResult(key);
return;
}
}
// Generate unique code
let code;
do {
code = generateCode();
} while (db.hasOwnProperty(code));
db[code] = url;
saveDB(db);
showResult(code);
});
function showResult(code) {
const shortURL = location.origin + location.pathname + '#/' + code;
resultDiv.innerHTML = `
Short URL: <a class="short-url" href="#/${code}">${shortURL}</a>
`;
resultDiv.style.display = 'block';
// auto-select the link on click for easy copy
const link = resultDiv.querySelector('a');
link.addEventListener('click', e => {
e.preventDefault();
window.location.hash = `#/${code}`;
});
}
}
// Handle hash route to redirect or show error
function handleRoute() {
const hash = location.hash; // format assumed: #/code or empty
if (!hash || hash === '#/' || hash === '') {
// Home Page
renderHome();
return;
}
const match = hash.match(/^#\/([A-Za-z0-9]{6})$/);
if (!match) {
// Invalid route, redirect to home
renderHome();
return;
}
const code = match[1];
const db = loadDB();
if (db.hasOwnProperty(code)) {
// Redirect to stored URL
window.location.href = db[code];
} else {
// Code not found: show error page with link to home
appDiv.innerHTML = `
<h1>URL not found</h1>
<p>The short URL code <strong>${code}</strong> does not exist.</p>
<p><a href="#/">Go back to home page</a></p>
`;
}
}
// Initial run
window.addEventListener('hashchange', handleRoute);
// On page load
handleRoute();
})();
</script>
</body>
</html>
index.html.http://localhost/index.html#/Ab3xYz).localStorage.Let me know if you want me to add features like:
Not yet included in a published release.