Browser APIs: Window and Navigation 🪟
Your Browser is Like a Control Room
Imagine you’re sitting in a spaceship control room. There are buttons everywhere! One button opens doors, another shows where you are in space, one remembers where you’ve been, and some buttons pop up messages to talk to the pilot.
That’s exactly what the browser gives you with JavaScript! The browser has special tools called APIs (Application Programming Interfaces) that let you control the webpage, just like buttons in a control room.
🪟 The Window Object: Your Main Control Panel
What is it?
The window object is like the main dashboard of your spaceship. It contains EVERYTHING in the browser. Every button, every screen, every tool—they all live inside window.
Think of it this way:
- Your room has walls, a door, a bed, toys
- The browser’s “room” is called
window - Inside it: the page, buttons, timers, messages—everything!
Simple Example
// The window knows how wide your screen is
console.log(window.innerWidth);
// Output: 375 (or whatever your screen width is)
// It knows your screen height too!
console.log(window.innerHeight);
// Output: 667
Cool Things Window Can Do
// Open a new browser window
window.open('https://example.com');
// Close the current window
window.close();
// Scroll to the top of the page
window.scrollTo(0, 0);
Fun Fact
You don’t even need to write window.! The browser knows what you mean:
// These do the same thing:
window.alert('Hello!');
alert('Hello!'); // Works too!
📍 The Location Object: Your GPS
What is it?
The location object is like your GPS navigator. It knows:
- Where you are (the current web address)
- How to take you somewhere else
- All the parts of your address
Understanding Web Addresses
A web address is like a home address, but for websites:
https://shop.example.com:8080/toys/cars?color=red#details
│ │ │ │ │ │
│ │ │ │ │ └─ hash (section)
│ │ │ │ └─ search (filters)
│ │ │ └─ pathname (folder/room)
│ │ └─ port (door number)
│ └─ hostname (building name)
└─ protocol (how to travel there)
Simple Example
// See the full address
console.log(location.href);
// "https://example.com/games"
// See just the website name
console.log(location.hostname);
// "example.com"
// See what page you're on
console.log(location.pathname);
// "/games"
Going Somewhere New
// Go to a new page (adds to history)
location.href = 'https://fun.com';
// Replace current page (no back button)
location.replace('https://fun.com');
// Refresh the page
location.reload();
⏪ The History API: Your Time Machine
What is it?
Remember when you clicked the back button in your browser? That’s the History API! It’s like a time machine that remembers every page you visited.
The Story
Imagine you’re reading a book:
- Page 1 → Page 2 → Page 3
- You can flip back to Page 2
- Or forward to Page 3 again
The browser does the same thing with websites!
Simple Example
// Go back one page (like clicking ←)
history.back();
// Go forward one page (like clicking →)
history.forward();
// Jump multiple pages
history.go(-2); // Go back 2 pages
history.go(3); // Go forward 3 pages
Modern Magic: pushState and replaceState
// Add a new "page" to history
// (without actually loading a new page!)
history.pushState(
{ page: 'games' }, // data to save
'', // title (ignored)
'/games' // new URL to show
);
// Replace current history entry
history.replaceState(
{ page: 'toys' },
'',
'/toys'
);
Listening for Back/Forward
// When user clicks back or forward:
window.addEventListener('popstate', (event) => {
console.log('You traveled in time!');
console.log(event.state);
});
🔍 The Navigator Object: Your Detective
What is it?
The navigator object is like a detective that knows all about the visitor:
- What browser are they using?
- What language do they speak?
- Are they online or offline?
- What device are they on?
Simple Example
// What browser is being used?
console.log(navigator.userAgent);
// "Mozilla/5.0 (iPhone; ..."
// What language does the user prefer?
console.log(navigator.language);
// "en-US"
// Are they connected to the internet?
console.log(navigator.onLine);
// true or false
// How many processor cores?
console.log(navigator.hardwareConcurrency);
// 8
Useful Navigator Features
// Check if user is online
if (navigator.onLine) {
console.log('You are online!');
} else {
console.log('No internet connection!');
}
// Get their location (asks permission!)
navigator.geolocation.getCurrentPosition(
(pos) => {
console.log(pos.coords.latitude);
console.log(pos.coords.longitude);
}
);
💬 Talking to Users: alert, confirm, prompt
The Three Messengers
Think of these as three different ways to talk to the person using your website:
| Method | What it does | User can… |
|---|---|---|
alert |
Shows a message | Click OK |
confirm |
Asks yes/no | Click OK or Cancel |
prompt |
Asks for text | Type something |
1. Alert: The Announcer 📢
// Just shows a message
alert('Welcome to my website!');
// User sees a popup, clicks OK
Think of it like a megaphone—it announces something, and everyone just listens.
2. Confirm: The Question Asker ❓
// Asks yes or no
let answer = confirm('Do you want pizza?');
if (answer === true) {
console.log('Yay! Pizza time!');
} else {
console.log('Maybe next time!');
}
It’s like asking “Do you want to play?” and waiting for Yes or No.
3. Prompt: The Information Gatherer 📝
// Asks for text input
let name = prompt('What is your name?');
if (name) {
console.log('Hello, ' + name + '!');
} else {
console.log('Hello, mysterious stranger!');
}
// You can also give a default answer
let age = prompt('How old are you?', '10');
It’s like passing a note that says “Write your name here: ______”
🎯 Quick Summary
graph TD A["Window Object"] --> B["Location"] A --> C["History"] A --> D["Navigator"] A --> E["Dialogs"] B --> B1["href - full address"] B --> B2["hostname - site name"] B --> B3["pathname - page path"] C --> C1["back/forward"] C --> C2["pushState"] C --> C3["popstate event"] D --> D1["userAgent"] D --> D2["language"] D --> D3["onLine status"] E --> E1["alert"] E --> E2["confirm"] E --> E3["prompt"]
🎮 Try It Yourself!
Open your browser’s console (F12 or right-click → Inspect → Console) and try:
// 1. Check your screen size
console.log(
'Width:', innerWidth,
'Height:', innerHeight
);
// 2. See your current location
console.log(location.href);
// 3. Check if you're online
console.log(
navigator.onLine ? 'Online!' : 'Offline!'
);
// 4. Say hello
let name = prompt('Your name?');
alert('Hello, ' + name + '!');
🌟 Remember This!
| API | Think of it as… | Main Job |
|---|---|---|
window |
Control Room | Contains everything |
location |
GPS | Knows & changes the URL |
history |
Time Machine | Back, forward, navigate |
navigator |
Detective | Info about browser/user |
alert |
Megaphone | Shows messages |
confirm |
Yes/No question | Gets true/false |
prompt |
Fill-in-the-blank | Gets text input |
You now have the keys to the control room! Every website you visit uses these tools. Now YOU can use them too! 🚀
