js_ex_browser
Interacting with the Browser: BOM Examples
Section titled “Interacting with the Browser: BOM Examples”The Browser Object Model (BOM) allows JavaScript to interact with the browser, outside the content of the HTML document itself. The BOM is not standardized like the DOM, but most modern browsers implement common BOM features.
The Window Object
Section titled “The Window Object”The window object represents the browser window or tab. It’s the global object in client-side JavaScript. Many of its properties and methods can be accessed without explicitly writing window..
- Open a new window:
window.open('url', 'windowName', 'features') - Control appearance of a new window (via
featuresstring inwindow.open) - Focus or blur a window:
window.focus(),window.blur() - Close a window:
window.close()(typically only works for windows opened by script) - Check if a window is closed:
myWindow.closed(boolean) - Interact with parent/opener window (e.g.,
window.opener) - Move a window:
window.moveTo(x, y),window.moveBy(dx, dy) - Resize a window:
window.resizeTo(width, height),window.resizeBy(dw, dh) - Print current page:
window.print() - Scroll content:
window.scrollTo(x, y),window.scrollBy(dx, dy)
Learn more about the window object and its extensive capabilities.
The Screen Object
Section titled “The Screen Object”The window.screen object contains information about the user’s screen.
- Screen width:
screen.width - Screen height:
screen.height - Available screen width (excluding OS interface like taskbar):
screen.availWidth - Available screen height:
screen.availHeight - Color depth:
screen.colorDepth(bits per pixel) - Pixel depth:
screen.pixelDepth(similar to color depth)
This information can be useful for responsive design decisions or analytics, but CSS media queries are generally preferred for styling based on screen characteristics.
The Location Object
Section titled “The Location Object”The window.location object provides information about the current URL and methods to navigate or reload the page.
- Full URL:
location.href(can also be set to navigate) - Protocol:
location.protocol(e.g., “http:”, “https:”) - Hostname:
location.hostname(e.g., “www.example.com”) - Port:
location.port - Pathname:
location.pathname(e.g., “/path/to/page.html”) - Search string (query parameters):
location.search(e.g., “?id=123&category=books”) - Hash (fragment identifier):
location.hash(e.g., “#section1”) - Load a new document:
location.assign('new_url')orlocation.href = 'new_url' - Reload the current page:
location.reload(forceGet)(true forces reload from server) - Replace current document (no history entry):
location.replace('new_url')
The URL object (new URL(urlString)) is a more modern and robust way to parse and manipulate URL components.
The History Object
Section titled “The History Object”The window.history object allows interaction with the browser’s session history.
- Number of URLs in history list:
history.length - Go back:
history.back()(equivalent to browser’s back button) - Go forward:
history.forward() - Go to a specific URL in history:
history.go(n)(e.g.,history.go(-1)is likeback())
Modern single-page applications (SPAs) often use the History API (history.pushState(), history.replaceState(), popstate event) for more sophisticated client-side routing.
The Navigator Object
Section titled “The Navigator Object”The window.navigator object contains information about the browser itself.
- Cookies enabled:
navigator.cookieEnabled(boolean) - User agent string:
navigator.userAgent(string identifying the browser, use with caution for feature detection) - Platform:
navigator.platform(e.g., “Win32”, “MacIntel”) - Language:
navigator.languageornavigator.languages(preferred language(s) of the user) - Online status:
navigator.onLine(boolean, indicates if browser has network connection) - Geolocation:
navigator.geolocation(provides access to user’s location, requires permission) - Clipboard API:
navigator.clipboard(for interacting with system clipboard, requires permission)
Best Practice: Instead of browser sniffing (parsing navigator.userAgent), prefer feature detection (checking if a specific object, method, or property exists and works as expected) to determine browser capabilities.
Popup Boxes (Legacy)
Section titled “Popup Boxes (Legacy)”JavaScript provides built-in functions for simple modal dialogs:
- Alert box:
alert('message')(displays a message and an OK button) - Confirm box:
confirm('message')(displays a message, OK, and Cancel buttons; returnstrueorfalse) - Prompt box:
prompt('message', 'defaultText')(displays a message, an input field, OK, and Cancel buttons; returns input string ornull)
While still functional, these native popups are often considered intrusive and have limited styling options. Modern web applications typically use custom-styled modals or dialogs (e.g., using HTML <dialog> element or UI libraries) for a better user experience.
Timing Events
Section titled “Timing Events”JavaScript allows you to execute code after a specified time interval or repeatedly at a fixed interval.
setTimeout(function, milliseconds, param1, param2, ...): Executesfunctiononce aftermilliseconds. Returns a timer ID.clearTimeout(timerID): Cancels asetTimeout()before it executes.setInterval(function, milliseconds, param1, param2, ...): Executesfunctionrepeatedly everymilliseconds. Returns an interval ID.clearInterval(intervalID): Stops asetInterval().
For smooth animations, requestAnimationFrame(callback) is preferred over setTimeout or setInterval. It tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint.
Client-Side Storage: Cookies and Web Storage
Section titled “Client-Side Storage: Cookies and Web Storage”Cookies (document.cookie) are small pieces of data stored on the user’s computer by the browser. They are sent with every HTTP request to the same domain. While useful for session management, they have size limitations and can impact performance if overused.
Modern alternatives for client-side storage include the Web Storage API:
localStorage: Stores data with no expiration time. Data persists even after the browser window is closed and reopened. (e.g.,localStorage.setItem('key', 'value');,localStorage.getItem('key');)sessionStorage: Stores data for one session only. Data is cleared when the browser tab is closed.
Web Storage offers larger storage capacity and a simpler API compared to cookies for client-side data that doesn’t need to be sent with every HTTP request. For more complex client-side data needs, IndexedDB provides a transactional database system.