Appearance
Browser Objects
JavaScript provides access to various browser objects for interaction and manipulation. Here are the key ones:
window
The window
object serves as the global scope and represents the browser window. You can get the internal dimensions using innerWidth
and innerHeight
, which exclude UI elements like menus. Use outerWidth
and outerHeight
for the entire window size. Compatibility: Not supported in IE<=8.
javascript
console.log('window inner size: ' + window.innerWidth + ' x ' + window.innerHeight);
navigator
The navigator
object holds information about the browser. Key properties include:
navigator.appName
: Browser name.navigator.appVersion
: Browser version.navigator.language
: Language setting.navigator.platform
: Operating system.navigator.userAgent
: User-Agent string.
javascript
console.log('appName = ' + navigator.appName);
Note: navigator
values can be modified by users, making version checks unreliable.
screen
The screen
object provides information about the user's screen:
screen.width
: Screen width in pixels.screen.height
: Screen height in pixels.screen.colorDepth
: Color depth in bits.
javascript
console.log('Screen size = ' + screen.width + ' x ' + screen.height);
location
The location
object represents the current page's URL. You can retrieve components like protocol, host, and pathname:
javascript
console.log(location.protocol); // 'http'
Use location.assign()
to load a new page or location.reload()
to refresh the current page.
document
The document
object represents the current page and serves as the root of the DOM tree. You can change the document title dynamically:
javascript
document.title = 'Learn JavaScript!';
To find DOM nodes, use methods like getElementById()
and getElementsByTagName()
.
javascript
let menu = document.getElementById('drink-menu');
history
The history
object stores the browser's session history. You can navigate back and forward using history.back()
and history.forward()
. For modern applications, use history.pushState()
to manage history with AJAX-loaded content:
javascript
history.pushState(state, '', newUrl);
References
Common browser objects include:
These objects enable developers to interact with the browser environment effectively.