JavaScript lesson

Build a browser app that inspects URL parts

Build a URL inspector from six complete files. See address parts, identify fragments and download a JSON report for three demo rules.

1. Start an empty folder with index.html

You will build an app that separates address parts. A URL is a web address; its fragment is the final part starting with #. You need only a browser and text editor, without a server or account.

Create url-baxis-v1. The six-file tree starts index.html. HTML defines structure; save the complete code as index.html. Keep all files together as UTF-8 without hidden .txt extensions.

Textindex.html
<!-- url-baxis-v1/
index.html
styles.css
content.js
core.js
app.js
tests.cjs
-->
<!doctype html>
<html lang="az">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>URL baxışı</title>
<link rel="stylesheet" href="styles.css">
<script defer src="content.js"></script>
<script defer src="core.js"></script>
<script defer src="app.js"></script>
</head>
<body>
<main>
<header><span>IT Innovations Academy · LAB 01</span>
<label><span data-word="language">Dil</span>
<select id="language"><option value="az">Azərbaycan</option><option value="en">English</option><option value="ru">Русский</option></select>
</label>
</header>
<h1 id="title" data-word="title">URL baxışı</h1>
<p id="intro" data-word="intro"></p>
<form id="form" novalidate>
<label for="url" data-word="url">URL</label>
<input id="url" maxlength="600" autocomplete="off" aria-describedby="hint" placeholder="https://example.org/callback">
<p id="hint" data-word="hint"></p>
<div class="actions"><button id="check" data-word="check" type="submit"></button><button id="clear" data-word="clear" type="button"></button></div>
</form>
<div class="samples"><button id="fragmentSample" type="button">https://example.org/callback#demo</button><button id="validSample" type="button">https://example.org/callback</button></div>
<p id="status" role="status" aria-live="polite"></p>
<section id="results" hidden aria-labelledby="resultTitle">
<h2 id="resultTitle" data-word="result"></h2>
<dl id="parts"></dl>
<ul id="flags"></ul>
</section>
<button id="download" data-word="download" type="button" disabled></button>
<footer><p id="note" data-word="note"></p><p id="source" data-word="source"></p></footer>
</main>
</body>
</html>

2. Add appearance with styles.css

CSS controls appearance. Save the complete code as styles.css. The page adapts to phone width, and colors follow your system’s light or dark setting.

Use Tab to reach the input and buttons; the focused control should have a visible outline.

Textstyles.css
* { box-sizing:border-box; }
:root { color-scheme:light dark; --bg:#f3f5f2; --card:white; --ink:#163f37; --line:#b5c7bd; }
body { margin:0; background:var(--bg); color:var(--ink); font:17px/1.5 system-ui,sans-serif; }
main { max-width:850px; margin:auto; padding:28px 22px; }
header,.actions,.samples { display:flex; gap:12px; flex-wrap:wrap; }
header { justify-content:space-between; font-size:13px; }
h1 { font-size:clamp(36px,7vw,62px); margin:42px 0 20px; }
form,section { padding:20px; border:1px solid var(--line); background:var(--card); }
label,dt,#status { font-weight:650; }
input,button,select { font:inherit; color:inherit; background:var(--card); border:1px solid var(--line); border-radius:7px; padding:10px; }
input { width:100%; margin-top:8px; }
button:disabled { opacity:.45; }
:focus-visible { outline:3px solid #d87900; outline-offset:3px; }
.samples,#download { margin-top:16px; }
.samples button,footer,#hint { font-size:13px; }
dl { display:grid; grid-template-columns:120px minmax(0,1fr); gap:8px; }
dd { margin:0; overflow-wrap:anywhere; }
[hidden] { display:none; }
@media(max-width:500px) { main { padding:18px 14px; } dl { grid-template-columns:1fr; } }
@media(prefers-color-scheme:dark) { :root { --bg:#102022; --card:#183033; --ink:#e4f0e7; --line:#46605c; } }

3. Store three languages in content.js

Save the complete code as content.js. It holds Azerbaijani, English and Russian labels. Language selection changes only the interface, without translating your input. Samples use the reserved example.org domain; the app never connects to it.

The GitHub announcement concerns a future change. Our three demo rules are HTTPS, no username/password and no literal #. Passing them does not establish complete security or compliance with a provider’s rules.

JavaScriptcontent.js
window.words = {
  az: {
    title:'URL baxışı', language:'Dil', intro:'Ünvanın hissələrini və üç yerli qaydanı öyrənin.',
    url:'Nümunə URL', hint:'Maksimum 600 simvol. Uydurma ünvan yazın; parol və açar yazmayın.',
    check:'Yoxla', clear:'Təmizlə', download:'JSON endir', blank:'URL daxil edin.',
    invalid:'Yanlış URL: hostlu tam ünvan, boşluqsuz, idarəetmə simvolusuz, ən çox 600 simvol.',
    pass:'Demo: üç qayda ödənir.', fail:'Demo: dəyişiklik lazımdır.', result:'Ünvanın hissələri',
    parts:['Protokol','Host','Yol','Sorğu','Fraqment'], flags:['HTTPS','Ad və parol yoxdur','Literal # yoxdur'],
    yes:'Bəli', no:'Xeyr', empty:'(yoxdur)',
    note:'Tədris demosu. GitHub girişi və tam təhlükəsizlik yoxlaması deyil. Şəbəkə və daimi yaddaş yoxdur.',
    source:'GitHub Changelog · 30.11.2026: redirect URI fraqmentlərinin ləğvi. Son # boş fraqmentdir; %23 yolun hissəsi ola bilər.'
  },
  en: {
    title:'URL inspector', language:'Language', intro:'Explore address parts and three local rules.',
    url:'Sample URL', hint:'600 characters maximum. Invented addresses only; no passwords or keys.',
    check:'Check', clear:'Clear', download:'Download JSON', blank:'Enter a URL.',
    invalid:'Invalid URL: full address with host, no whitespace or control characters, maximum 600 characters.',
    pass:'Demo: all three rules pass.', fail:'Demo: changes needed.', result:'Address parts',
    parts:['Protocol','Host','Path','Query','Fragment'], flags:['HTTPS','No username or password','No literal #'],
    yes:'Yes', no:'No', empty:'(none)',
    note:'Learning demo. No GitHub login or complete security check. No network or persistent storage.',
    source:'GitHub Changelog · 2026-11-30: deprecating redirect URI fragments. Trailing # is an empty fragment; %23 may be part of a path.'
  },
  ru: {
    title:'Разбор URL', language:'Язык', intro:'Изучите части адреса и три локальных правила.',
    url:'Учебный URL', hint:'До 600 символов. Выдуманные адреса; без паролей и ключей.',
    check:'Проверить', clear:'Очистить', download:'Скачать JSON', blank:'Введите URL.',
    invalid:'Неверный URL: полный адрес с хостом, без пробелов и управляющих символов, до 600 символов.',
    pass:'Демо: три правила выполнены.', fail:'Демо: нужны изменения.', result:'Части адреса',
    parts:['Протокол','Хост','Путь','Запрос','Фрагмент'], flags:['HTTPS','Нет имени и пароля','Нет буквального #'],
    yes:'Да', no:'Нет', empty:'(нет)',
    note:'Учебное демо. Без входа GitHub и полной проверки безопасности. Нет сети и постоянного хранения.',
    source:'GitHub Changelog · 30.11.2026: отказ от фрагментов redirect URI. Конечный # — пустой фрагмент; %23 может быть частью пути.'
  }
};

4. Parse the address with core.js

JavaScript controls behavior in the browser. Save the complete code as core.js. The URL constructor separates address parts. valid means parsing succeeded; pass means all three demo rules were satisfied.

A trailing bare # is an empty fragment. %23 can instead be an encoded character in the path, not a fragment delimiter. The code preserves that distinction. Blank input has its own state; whitespace, controls, missing hosts and malformed addresses are rejected.

JavaScriptcore.js
(function (scope) {
  'use strict';
  function inspect(raw) {
    if (raw === '') return { state: 'blank' };
    if (typeof raw !== 'string' || raw.length > 600 || /[\s\u0000-\u001f\u007f-\u009f]/u.test(raw)) {
      return { state: 'invalid' };
    }
    let url;
    try { url = new URL(raw); } catch { return { state: 'invalid' }; }
    if (!url.hostname) return { state: 'invalid' };
    const flags = {
      https: url.protocol === 'https:',
      credentials: !url.username && !url.password,
      fragment: !raw.includes('#')
    };
    return {
      state: 'valid',
      parts: {
        protocol: url.protocol,
        hostname: url.hostname,
        path: url.pathname,
        query: url.search,
        fragment: raw.includes('#') ? raw.slice(raw.indexOf('#')) : ''
      },
      flags,
      pass: Object.values(flags).every(Boolean)
    };
  }
  if (typeof module !== 'undefined') module.exports = { inspect };
  else scope.UrlLab = { inspect };
})(typeof globalThis !== 'undefined' ? globalThis : this);

5. Open the working product with app.js

Save the complete code as app.js, then open index.html in your browser. Choose the first, fragmented sample: expect host example.org, path /callback and fragment #demo. HTTPS and credentials rules show Yes, while the literal # rule shows No. The second sample gives three Yes results.

Enter just x as invalid input: expect an error and a disabled JSON button. Clear hides results and focuses the input. For a parsed address, Download JSON creates url-demo-report.json even when a rule shows No. JSON is a text format with named fields.

JavaScriptapp.js
'use strict';
const byId = id => document.getElementById(id);
const input = byId('url');
let report = { state: 'blank' };
function render() {
  const lang = byId('language').value;
  const w = window.words[lang];
  document.documentElement.lang = lang;
  document.title = w.title;
  document.querySelectorAll('[data-word]').forEach(el => {
    el.textContent = w[el.dataset.word];
  });
  byId('language').setAttribute('aria-label', w.language);
  const valid = report.state === 'valid';
  byId('results').hidden = !valid;
  byId('download').disabled = !valid;
  byId('status').textContent = valid ? w[report.pass ? 'pass' : 'fail'] : w[report.state];
  byId('parts').replaceChildren();
  byId('flags').replaceChildren();
  if (!valid) return;
  Object.values(report.parts).forEach((value, i) => {
    const term = document.createElement('dt');
    const detail = document.createElement('dd');
    term.textContent = w.parts[i];
    detail.textContent = value || w.empty;
    byId('parts').append(term, detail);
  });
  Object.values(report.flags).forEach((value, i) => {
    const item = document.createElement('li');
    item.textContent = `${w.flags[i]}: ${value ? w.yes : w.no}`;
    byId('flags').append(item);
  });
}
function check() { report = UrlLab.inspect(input.value); render(); }
byId('form').addEventListener('submit', event => { event.preventDefault(); check(); });
input.addEventListener('input', check);
byId('language').addEventListener('change', render);
byId('clear').addEventListener('click', () => { input.value = ''; check(); input.focus(); });
for (const [id, value] of [['fragmentSample','https://example.org/callback#demo'], ['validSample','https://example.org/callback']]) {
  byId(id).addEventListener('click', () => { input.value = value; check(); input.focus(); });
}
byId('download').addEventListener('click', () => {
  if (report.state !== 'valid') return;
  const file = new Blob([JSON.stringify(report, null, 2)], { type: 'application/json' });
  const url = URL.createObjectURL(file);
  const link = document.createElement('a');
  link.href = url;
  link.download = 'url-demo-report.json';
  link.click();
  setTimeout(() => URL.revokeObjectURL(url), 1000);
});
render();

6. Check tests.cjs and explore one difference

Save the complete code as tests.cjs. If Node is installed, run node tests.cjs. The actual Node 24.19.0 run printed URL core: all assertions passed. Node is not needed to open the app. Enter also checks input in the browser. The limit is 600 JavaScript text units; some characters use two units.

Exercise: replace #demo in the first sample with %23demo. Expect path /callback%23demo, an empty fragment and three Yes results. Append a bare # again: the fragment rule becomes No. The app does not check site availability, domain ownership or redirects. Do not enter private data or real keys; the app does not save input in persistent storage.

JavaScripttests.cjs
const a = require('node:assert/strict');
const { inspect: check } = require('./core.js');
const base = 'https://example.org/callback';
a.deepEqual(check(''), { state:'blank' });
for (const raw of [' ', 'x', 'https://', 'file:///x', 'https://a b', 'https://a\nx', 'https://a\u0000', 'https://a\u0085', 'https://a\u00a0b', null]) {
  a.equal(check(raw).state, 'invalid');
}
for (const suffix of ['', '%23demo', '?q=%23demo']) a.equal(check(base + suffix).pass, true);
a.equal(check('https://例え.テスト/öyrən').pass, true);
a.equal(check('http://example.org').flags.https, false);
a.equal(check('https://user:[email protected]').flags.credentials, false);
a.equal(check(base + '#').flags.fragment, false);
a.equal(check(base + '#').parts.fragment, '#');
a.equal(check(base + '#demo').pass, false);
a.equal(check('https://a/' + 'a'.repeat(590)).state, 'valid');
a.equal(check('https://a/' + 'a'.repeat(591)).state, 'invalid');
a.equal('parts' in check(''), false);
a.equal('parts' in check('bad'), false);
console.log('URL core: all assertions passed');

Recommended reading

All articles