Browser and Networking
Browser and Networking
- Event delegation, capturing, and bubbling in the browser
- Event delegation: Attach one listener on the parent and let it handle events from child elements. This avoids binding many listeners directly on each child.
- Event capturing: Events travel downward from
Window → document → parent → child. The outer layers receive the event earlier, providing a chance to block default browser actions before they occur (e.g., prevent scrolling, prevent drag, cancel default navigation). - Event bubbling (most common): Events travel upward from the target element → parent → grandparent. By default, all event listeners run in the bubbling phase. This allows parent components to centrally manage child behavior rather than scattering listeners across nodes.
- target vs currentTarget:
event.target: the element that actually triggered the event (never changes)event.currentTarget: the element whose listener is currently running (changes during propagation)
- Stopping propagation:
event.stopPropagation(): stops further bubblingevent.stopImmediatePropagation(): stops bubbling + prevents other listeners on the same element from executing
- Timing of DOMContentLoaded, load, beforeunload, unload
- DOMContentLoaded: Fires when the DOM tree is fully built (CSS/images not required). Ideal for binding events and running DOM-dependent JS.
- load: Fires after all resources (images, CSS, fonts) have finished loading. Used for logic dependent on full resource availability.
- beforeunload: Fires right before the user leaves (can still interrupt). Useful for preventing data loss and showing confirmation dialogs.
- unload: Fires when the page is being unloaded. Used for final cleanup, though modern apps avoid relying on it.
- Differences between cookie, sessionStorage, and localStorage
- Only cookies are sent to the server → used for login and authentication.
localStorageandsessionStorageare never sent to the server. - Expiration behavior:
- cookie → configurable expiration, typically for server session
- localStorage → persistent
- sessionStorage → per-tab, cleared when tab closes
- Capacity:
- cookie ~4 KB (very small)
- storage ~5–10 MB (suitable for large frontend data)
- Difference between localStorage and IndexedDB
- localStorage: small, synchronous, string-only, simple key-value storage.
- IndexedDB: large, asynchronous, can store any structured data, a full local database.
- What happens after entering a URL and pressing Enter?
- Parse URL: Browser extracts protocol, domain, path, etc.
- DNS lookup: Browser resolves the domain to an IP using cache + DNS resolver (Root → TLD → Authoritative), with TTL-controlled caching.
- Connection & transport: Establish TCP/TLS connection; packets are routed across multiple network nodes like logistics hubs.
- HTTP request/response: Browser sends an HTTP request; the server returns a response (status + headers + body).
- Browser rendering: Parse HTML, load CSS/JS/resources, build DOM & CSSOM, layout, paint, run JS, and render the final page.
HTTP, HTTPS, CORS
- Differences among HTTP/1, HTTP/1.1, HTTP/2, HTTP/3
- HTTP/1 → HTTP/1.1: HTTP/1.1 fixes repeated connections, bandwidth waste, weak caching, virtual host issues, and insufficient methods.
- HTTP/1.1 → HTTP/2: Solves head-of-line blocking at the HTTP layer, header redundancy, multiple RTTs, and lack of prioritization.
- HTTP/2 → HTTP/3:
- HTTP/2 uses TCP → if one TCP packet is lost, the entire connection stalls.
- HTTP/3 uses QUIC (based on UDP) → each stream retransmits independently; packet loss does not block others.
- Also improves handshake speed, connection migration, and congestion control.
- What is CORS? Why do we need it?
CORS is the browser’s cross-origin security mechanism.
The Same-Origin Policy blocks JS from reading cross-origin responses by default, but real applications must make cross-origin requests.
The server uses CORS headers to tell the browser which origins may access its resources.
Two types: simple requests and preflight requests. Preflight = an automatic OPTIONS request the browser sends to verify safety before sending the real request.
To fix CORS: the backend must return correct CORS headers.
Example:
- DELETE request is not simple → browser sends OPTIONS first
- If server agrees via CORS headers → real DELETE is sent
- If not → browser blocks it (request never leaves the browser)
- Explain HTTP caching mechanisms
- Browsers cache previously requested data. If unchanged, the browser can reuse the cached copy instead of re-requesting.
Strong caching (browser uses cache without sending a request)
Controlled by Cache-Control:
Cache-Control: max-age=60→ valid for 60 secondsno-store→ must always re-request; cannot store responsepublic, max-age=86400→ cacheable by any layer (browser, proxy, CDN)private, max-age=600→ cacheable only by the browsermax-age=60, must-revalidate→ once expired, must revalidate with serverno-cache→ cached but must validate before use (negotiated cache)
Negotiated caching
When the cache expires, browser asks server if data changed:
- ETag → like a fingerprint of the resource
- Last-Modified → timestamp of the file’s last update
- HTTP status codes every frontend/back-end developer must know
- 1xx informational: 100 continue; 101 switching protocols
- 2xx success: 200 OK; 201 Created; 204 No Content
- 3xx redirect:
- 301 permanent redirect (browser caches it)
- 302 temporary redirect
- 304 Not Modified (use cached version)
- 4xx client errors:
- 401 unauthorized (need login)
- 403 forbidden (logged in but insufficient permission)
- 404 not found
- 5xx server errors:
- 500 server crash/bug
- 501 not implemented
- 503 service unavailable (server overloaded)
Information Security
- What is a DDoS attack?
- Distributed Denial of Service: uses massive malicious traffic to overwhelm a target server or website.
- Defenses: larger capacity, blocking via reverse proxy/CDN, automated traffic filtering and scrubbing.
- What is XSS? How to prevent it?
- XSS is not “hackers inserting code into your server.”
- XSS happens when the server naïvely stores unescaped user input and later delivers it to other users, causing the browser to execute unwanted scripts.
Types of XSS
- Stored XSS: Server stores malicious input (e.g., in a database) and later sends it to users.
- Reflected XSS: No database involved; malicious input is reflected via URL or immediate response. Occurs when backend/frontend inject unescaped data into HTML.
- DOM XSS: Occurs purely on the client side when the frontend inserts untrusted data into
innerHTML.
- What is CSRF? How to prevent it?
- Cross-Site Request Forgery: attacker forces the victim’s browser (while logged in) to send malicious requests without their knowledge.
- Primary defense: CSRF Tokens
- What is SQL Injection? How to prevent it?
- Attackers craft malicious SQL fragments and inject them into user inputs, causing the backend to execute unintended SQL—bypassing login, reading tables, or deleting data.
- Prevention: parameterized queries / prepared statements (placeholders)
- Difference between encryption, encoding, and hashing
- Encoding: represent data differently; example: Morse code
- Encryption:
- public key encrypts, private key decrypts
- private key signs, public key verifies
- Hashing: transforms a file into a fixed-length fingerprint to check integrity