Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIAi2 WildChat-4.8M (AI2)

html css js url shortener SharedStorage "#/"

  1. User

    html css js url shortener SharedStorage "#/"

  2. Assistant

    It sounds like you want to build a simple URL shortener using HTML, CSS, and JavaScript, and you want the URL short codes or hashes to be stored or shared in the browser using something like the SharedStorage API or using the fragment identifier (# followed by a code) for routing or referencing.

    Let's clarify a few things and then provide an example:

    • URL shortener basics: You usually have a way to take a long URL and generate a short code (like abc123) and then redirect anyone hitting yourdomain.com/#abc123 to the long URL.

    • SharedStorage API: This is a new-ish web API allowing browsers to share storage across origins or tabs under privacy constraints. It's complex and not widely supported yet. For a simple demo, localStorage or sessionStorage or just embedding data in the URL hash (#abc123) is much simpler.

    • Using # in URL: We can put the shortcode in the fragment /#abc123 and parse it client-side to perform lookup and redirect or display.


    Minimal Example of a Frontend-Only URL Shortener

    This example uses:

    • A mapping object in JavaScript for shortcode → full URL (this can't persist after reload unless using localStorage)
    • Uses the URL hash (#shortcode) to redirect or show the mapped URL
    • Simple UI to add new shortcodes & URLs

    <!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: 600px; margin: 2rem auto; padding: 1rem; }
      label, input, button { display: block; margin-bottom: 0.5rem; }
      input { width: 100%; padding: 0.4rem; font-size: 1rem; }
      button { padding: 0.6rem 1.2rem; font-size: 1rem; cursor: pointer; }
      .message { margin-top: 1rem; color: green; }
      .error { color: red; }
    </style>
    </head>
    <body>
    
    <h1>Simple URL Shortener</h1>
    
    <form id="shortener-form">
      <label for="code">Shortcode (e.g., "abc123"):</label>
      <input type="text" id="code" name="code" pattern="^[a-zA-Z0-9_-]{3,15}$" title="3-15 chars, letters, numbers, _ or -" required />
      
      <label for="url">URL to shorten:</label>
      <input type="url" id="url" name="url" placeholder="https://example.com" required />
      
      <button type="submit">Add Shortcode</button>
    </form>
    
    <div class="message" id="message"></div>
    
    <script>
    // Load URL map from localStorage or start empty
    const STORAGE_KEY = 'url_map';
    let urlMap = JSON.parse(localStorage.getItem(STORAGE_KEY)) || {};
    
    // Save urlMap to localStorage
    function saveMap() {
      localStorage.setItem(STORAGE_KEY, JSON.stringify(urlMap));
    }
    
    // Redirect if hash present
    function tryRedirect() {
      const hash = location.hash.slice(1);
      if (!hash) return;
    
      if (urlMap[hash]) {
        // Redirect after a tiny delay to show a message
        document.body.innerHTML = `<p>Redirecting to <a href="${urlMap[hash]}" target="_blank" rel="noopener">${urlMap[hash]}</a> ...</p>`;
        setTimeout(() => {
          window.location.href = urlMap[hash];
        }, 1000);
      } else {
        document.body.innerHTML = `<p class="error">No URL found for shortcode: <code>${hash}</code></p>`;
      }
    }
    
    // Handle form submit
    document.getElementById('shortener-form').addEventListener('submit', e => {
      e.preventDefault();
      const codeInput = e.target.code.value.trim();
      const urlInput = e.target.url.value.trim();
    
      // Basic validation done by input pattern & type, but double check code is not taken
      if (urlMap[codeInput]) {
        showMessage(`Shortcode "${codeInput}" already exists. Choose another.`, true);
        return;
      }
    
      urlMap[codeInput] = urlInput;
      saveMap();
      
      showMessage(`Added shortcode: <code>${codeInput}</code> → <a href="${urlInput}" target="_blank" rel="noopener">${urlInput}</a>`, false);
    
      // Clear form
      e.target.reset();
    
      // Optionally update URL to the shortcode
      // location.hash = '#' + codeInput;
    });
    
    // Show status messages
    function showMessage(msg, error = false) {
      const msgEl = document.getElementById('message');
      msgEl.innerHTML = msg;
      msgEl.className = error ? 'message error' : 'message';
    }
    
    // Run redirect check at load
    tryRedirect();
    </script>
    
    </body>
    </html>
    

    How this works:

    • You open the page at (e.g.) index.html.
    • Add a shortcode/url pair like:
      • shortcode: abc123
      • URL: https://example.com
    • It stores it in localStorage.
    • Then, you can visit the page with hash like index.html#abc123
    • The script intercepts hash and redirects to the stored URL.
    • If no shortcode found it shows an error message.

    Limitations:

    • This is client-side only, no server or database.
    • Data saved in your browser's localStorage only; if you clear storage or use another device/user, data doesn't persist.
    • No real "short domain" redirection — to do this properly you need a backend to store links and redirect properly.

    If you want to build a more practical, server-backed URL shortener:

    • Store shortcodes & URLs in a database
    • Backend (Node.js, Python, PHP, etc) redirects directly on HTTP requests to https://yourdomain.com/abc123
    • Optionally a frontend UI to create entries.

    If you want me to help with a backend example or more advanced features, let me know!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.