JavaScript Browser
Working with browser objects and APIs
🌐 Browser Objects
JavaScript can interact with the browser through built-in objects like window, document, navigator, and location. These objects provide access to browser features and information.
// Get browser information
console.log("Browser: " + navigator.userAgent);
console.log("Current URL: " + window.location.href);
Try it:
Main Browser Objects
Window Object
The global browser window
window.alert("Hello!");
window.open("page.html");
Document Object
The HTML document
document.title = "New Title";
document.getElementById("demo");
Navigator Object
Browser information
navigator.userAgent;
navigator.language;
Location Object
Current page URL
location.href;
location.reload();
🔹 Window Object Methods
The window object provides methods to interact with the browser window:
// Alert dialog
window.alert("This is an alert!");
// Confirm dialog
var result = window.confirm("Are you sure?");
if (result) {
console.log("User clicked OK");
}
// Prompt dialog
var name = window.prompt("What's your name?");
console.log("Hello " + name);
// Open new window
window.open("https://example.com", "_blank");
Try it:
🔹 Navigator Object
Get information about the user's browser:
// Browser information
console.log("Browser name: " + navigator.appName);
console.log("Browser version: " + navigator.appVersion);
console.log("User agent: " + navigator.userAgent);
console.log("Language: " + navigator.language);
console.log("Online: " + navigator.onLine);
// Check if cookies are enabled
console.log("Cookies enabled: " + navigator.cookieEnabled);
Your Browser Info:
🔹 Location Object
Work with the current page URL:
// Get URL information
console.log("Full URL: " + location.href);
console.log("Protocol: " + location.protocol);
console.log("Host: " + location.host);
console.log("Pathname: " + location.pathname);
// Navigate to different pages
location.href = "newpage.html"; // Go to new page
location.reload(); // Reload current page
location.replace("page.html"); // Replace current page
Current Page Info:
🔹 Timing Functions
Execute code after a delay or repeatedly:
// Execute once after delay
setTimeout(function() {
alert("This runs after 3 seconds");
}, 3000);
// Execute repeatedly
var interval = setInterval(function() {
console.log("This runs every 2 seconds");
}, 2000);
// Stop the interval
clearInterval(interval);
Try it:
Counter: 0