Common Browser Objects in BOM
The location object is a property of the window object that represents the browser's address bar. It allows manipulation of the URL displayed in the address bar.
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
function handleLocation() {
console.log(location.host); // Server IP and port
console.log(location.hostname); // IP address
console.log(location.port); // Port number
console.log(location.href); // Full URL
location.href = "https://www.baidu.com";
}
</script>
</head>
<body>
<input type="button" value="Test Location" onclick="handleLocation()" />
</body>
</html>
The history object, also a property of the window object, maintains the browesr's navigation history. It enables control over browsing history navigation.
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
function navigateForward() {
window.history.forward();
}
function navigateBack() {
history.back();
}
function jumpToPage() {
history.go(2); // Positive number moves forward, negative moves backward
}
</script>
</head>
<body>
<a href="a.html" target="_self">pageA</a>
<input type="button" value="Forward" onclick="navigateForward()"/>
<input type="button" value="Back" onclick="navigateBack()"/>
<input type="button" value="Go" onclick="jumpToPage()"/>
</body>
</html>
The screen and navigator objects provide information about the display and browser environment respectively. Screen data includes dimensions, while navigator provides browser identification details.
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script>
function displayInfo() {
console.info(window.screen.width);
console.info(window.screen.height);
console.info(navigator.userAgent);
console.info(navigator.appName);
}
</script>
</head>
<body onload="displayInfo()">
</body>
</html>