Certainly! Below is a simple URL shortener created using HTML, CSS, and JavaScript that works entirely client-side. It uses a basic hash-based approach (#/<short-code>) to represent shortened URLs. When you enter a long URL, the app generates a short code, updates the URL hash (window.location.hash), and stores the mapping in localStorage. Visiting the page with a hash will redirect you to the original URL.
Features:
- Generates a short code (like
abc123)
- Stores mappings in
localStorage
- Supports sharing/seed via URL hash (e.g.,
yourdomain.com/#/abc123)
- Redirects automatically if visiting with a hash
How it works:
- Enter URL → generate a short code → save in localStorage → update hash → show short URL
- Visit the page with
#/<code> → redirect to original URL if found
Here is the complete code:
<!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: 50px auto;
padding: 20px;
background: #f9f9f9;
}
h1 {
text-align: center;
color: #333;
}
label, input, button {
display: block;
width: 100%;
margin: 10px 0;
}
input {
padding: 10px;
font-size: 16px;
}
button {
background-color: #008CBA;
color: white;
padding: 11px;
font-size: 18px;
border: none;
cursor: pointer;
}
button:hover {
background-color: #005f6a;
}
#short-url {
margin-top: 20px;
word-break: break-all;
font-weight: bold;
}
#error {
color: red;
}
</style>
</head>
<body>
<h1>Simple URL Shortener</h1>
<label for="longUrl">Enter URL to shorten:</label>
<input id="longUrl" type="url" placeholder="https://example.com" required />
<button id="shortenBtn">Shorten</button>
<div id="short-url"></div>
<div id="error"></div>
<script>
// Function to generate random short code (6 chars)
function generateCode(length = 6) {
const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
let result = '';
for(let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
}
// Validate URL format
function isValidUrl(string) {
try {
new URL(string);
return true;
} catch(e) {
return false;
}
}
// Save mapping to localStorage
function saveUrl(code, url) {
// Retrieve store or init
let store = JSON.parse(localStorage.getItem('url-shortener')) || {};
store[code] = url;
localStorage.setItem('url-shortener', JSON.stringify(store));
}
// Retrieve long URL from code
function getUrlByCode(code) {
const store = JSON.parse(localStorage.getItem('url-shortener')) || {};
return store[code];
}
// Update UI with the short url
function displayShortUrl(code) {
const shortUrl = `${location.origin}${location.pathname}#/${code}`;
const shortUrlDiv = document.getElementById('short-url');
shortUrlDiv.innerHTML = `Short URL: <a href="${shortUrl}">${shortUrl}</a>`;
}
// Handle redirection if hash in URL
function handleRedirect() {
const hash = location.hash;
if(hash.startsWith('#/')) {
const code = hash.slice(2);
const longUrl = getUrlByCode(code);
if(longUrl) {
// Redirect to original URL
window.location.href = longUrl;
} else {
document.getElementById('error').innerText = `No URL found for code: ${code}`;
}
}
}
document.getElementById('shortenBtn').addEventListener('click', () => {
const input = document.getElementById('longUrl');
const url = input.value.trim();
const errorDiv = document.getElementById('error');
errorDiv.innerText = '';
document.getElementById('short-url').innerText = '';
if(!isValidUrl(url)) {
errorDiv.innerText = 'Please enter a valid URL including the protocol (http:// or https://)';
return;
}
// Try generate unique code
let code;
let store = JSON.parse(localStorage.getItem('url-shortener')) || {};
do {
code = generateCode();
} while(store[code]);
// Save the URL
saveUrl(code, url);
// Update hash to the short code
location.hash = `#/${code}`;
// Show shortened URL
displayShortUrl(code);
});
// Run redirect check on page load
window.onload = handleRedirect;
</script>
</body>
</html>
How to Use
- Open this page in a modern browser.
- Enter a valid URL (e.g.,
https://openai.com) and click Shorten.
- It will show a shortened URL with a hash like
https://yourdomain.com/#/abc123.
- Visiting or sharing this shortened URL will redirect to the original URL automatically.
- The mappings persist in
localStorage per browser, so different users won’t share data unless they use the same browser profile.
Notes:
- This is a pure client-side demo. For real URL shorteners, you need a backend and database.
- The short code is random and 6 characters long.
- This is a minimal "seed/share" style shortener that uses the hash portion of the URL.
localStorage size limits and security apply.
- URLs are redirected using JavaScript on page load.
If you want me to help build a backend version or add features, just ask!