JavaScript Browser Object Model - Exercise 2

Use window.innerWidth to read the width of the page's viewport in CSS pixels. It excludes browser chrome and is useful when layout logic needs the visible content width.

javascript

const viewportWidth = window.innerWidth;
console.log(viewportWidth);

innerWidth measures the viewport area used to render the document, while outerWidth measures the entire browser window, including browser chrome. Values can change when the window is resized, so read them when needed rather than assuming they are constant.

javascript

console.log(window.innerWidth);
console.log(window.outerWidth);

Use location.replace() to load a new page without keeping the current page as a separate history entry. This is useful after a redirect because the user cannot return to the intermediate page with Back.

javascript

location.replace('/login/');

history.forward() moves the browser to the next page in session history, if one exists. It has no effect when the current page is already the newest history entry.

javascript

history.forward();

history.pushState() adds a new history entry and updates the address bar, but it does not trigger a page reload by itself.

javascript

history.pushState({ page: 'profile' }, '', '/profile');

Single-page interfaces often change the URL without reloading, so handling popstate lets the UI stay in sync when the user clicks the browser's Back or Forward buttons.

javascript

window.addEventListener('popstate', () => {
  renderRoute(location.pathname);
});

Use window.open(), usually in response to a user action such as a button click. Browsers may block calls made outside a user gesture, and the returned window reference can be null when opening is denied.

javascript

window.open('https://example.com', '_blank');

Browsers often block popups that are not triggered directly by a user gesture because unsolicited windows are a common spam and abuse pattern.

javascript

button.addEventListener('click', () => {
  window.open('/help/', '_blank');
});

You can check navigator.onLine and listen for the online and offline events, though this is only a basic signal and not a guarantee that every network request will succeed.

javascript

console.log(navigator.onLine);

window.addEventListener('offline', () => {
  console.log('Connection lost');
});

It exposes a browser-provided identification string that may include browser, rendering engine, operating system, and device details. It can be spoofed, so feature detection is usually safer.

javascript

console.log(navigator.userAgent);
All sections expanded. Activate the control to collapse all sections.