HistoryAPI
window.history objectwindow.history is a built-in object provided by the browser, which provides access to and operation capabilities of the browser history. Through this object, developers can implement page jumps without refreshing, add new browsing history entries, etc., thereby improving the user experience of single-page applications (SPAs). The main methods and properties include:
history.length: Returns the total number of entries in the browser history.history.back(): Equivalent to clicking the browser’s “back” button to return to the previous page.history.forward(): Equivalent to clicking the browser’s “forward” button to jump to the next page.history.go(n): n can be positive, negative, or 0. A positive number means jumping forward a number of history records, a negative number means jumping backward, and 0 is equivalent to refreshing the current page.
history.pushState() and history.replaceState()
These two methods allow developers to add or replace the state of the current page in the browser history without triggering an actual reload of the page. This allows SPAs to change URLs as the user navigates while maintaining application state, enabling support for browser forward/back buttons and address bar updates.
history.pushState(stateObject, title[, url]): Adds a new browsing history entry to the top of the history stack, updating the current URL.stateObjectis an arbitrary JavaScript object associated with the state, used to store state data;title(currently ignored by most browsers) is used to set the title of the history record, but browsers do not actually change the title of the tab; url (optional) is a new URL, relative to the URL of the current page.history.replaceState(stateObject, title[, url]): Similar topushState(), but instead of adding a new entry, the current history state is replaced. This means that the user cannot return to the previous state by pressing the back button.
Geolocation API
HTML5 Geolocation API allows web applications to access the device’s geolocation information with user permission. This provides the basis for location-based services (LBS) and map-related applications.
navigator.geolocation objectnavigator.geolocation is a property of the navigator object that contains methods for obtaining geolocation information.
getCurrentPosition(successCallback, errorCallback, options): Asynchronously obtain the user’s current location. If successful,successCallbackis called, passing in a GeolocationPosition object containing coordinates, accuracy, etc.; if an error occurs,errorCallbackis called, passing in aGeolocationPositionErrorobject. Theoptionsparameter is used to specify the configuration items of the positioning request, such as the maximum waiting time, the required accuracy, etc.watchPosition(successCallback, errorCallback, options): Similar togetCurrentPosition(), but will continue to monitor the user’s location and callsuccessCallbackeach time the location updates. Returns a listener ID, which can be stopped by theclearWatch()method.clearWatch(watchId): Pass the listener ID returned bywatchPosition()to stop the corresponding position monitoring.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Geolocation API Example</title>
</head>
<body>
<h1>Geolocation API Example</h1>
<button id="locateButton">Get Location</button>
<div id="locationInfo" style="margin-top: 20px;"></div>
<script src="geolocation-api.js"></script>
</body>
</html>geolocation-api.js
document.getElementById('locateButton').addEventListener('click', function() {
// Clear the previous location information
document.getElementById('locationInfo').innerHTML = '';
// Request location information
navigator.geolocation.getCurrentPosition(
displayLocation, // Success callback
handleLocationError // Failure callback
);
});
function displayLocation(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
const accuracy = position.coords.accuracy;
// Display longitude and latitude information
document.getElementById('locationInfo').innerHTML += `<p>Latitude: ${latitude}, Longitude: ${longitude}</p>`;
document.getElementById('locationInfo').innerHTML += `<p>Accuracy: ${accuracy} meters</p>`;
// Use Geocoding API (such as Google Maps Geocoding API) to convert coordinates to address information (this part of the code is not provided and needs to be implemented by yourself)
// getAddressFromCoordinates(latitude, longitude).then(address => {
// document.getElementById('locationInfo').innerHTML += `<p>Address: ${address}</p>`;
// });
}
function handleLocationError(error) {
let errorMessage = '';
switch (error.code) {
case error.PERMISSION_DENIED:
errorMessage = 'User denied the request for Geolocation.';
break;
case error.POSITION_UNAVAILABLE:
errorMessage = 'Location information is unavailable.';
break;
case error.TIMEOUT:
errorMessage = 'The request to get user location timed out.';
break;
default:
errorMessage = 'An unknown error occurred.';
}
document.getElementById('locationInfo').innerHTML = `<p>Error: ${errorMessage}</p>`;
}Fullscreen API
The fullscreen API allows web applications to put specified elements (such as videos, games, or entire pages) in fullscreen mode in the browser to provide an immersive user experience.
Fullscreen related methods and events
element.requestFullscreen(): Put the specified element into fullscreen mode. Different browsers may need to use specific prefixes (such aswebkitRequestFullscreen(), mozRequestFullScreen(), etc.).document.exitFullscreen(): Exit fullscreen mode. There may also be browser prefix versions.document.fullscreenElement: Returns the element currently in fullscreen mode, ornullif no element is in fullscreen mode.
Fullscreen events:
fullscreenchange: Triggered when the fullscreen state changes (enters or exits fullscreen).fullscreenerror: Triggered when an attempt to enter fullscreen mode fails.
To ensure cross-browser compatibility, it is usually necessary to detect and adapt to the implementation differences of different browsers, use methods such as element.requestFullscreen().catch(handleError) to handle possible errors, and listen to the corresponding full-screen events to make corresponding interface adjustments.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fullscreen API Example</title>
<style>
.fullscreen-button {
position: absolute;
top: 20px;
right: 20px;
}
</style>
</head>
<body>
<video id="videoElement" controls>
<source src="your-video-file.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<button class="fullscreen-button">Toggle Fullscreen</button>
<script src="fullscreen-api.js"></script>
</body>
</html>fullscreen-api.js
const fullscreenButton = document.querySelector('.fullscreen-button');
const targetElement = document.getElementById('videoElement'); // Or select other elements that need full screen
// Determine whether the full screen state is currently in progress
function isFullscreen() {
return document.fullscreenElement ||
document.webkitFullscreenElement ||
document.mozFullScreenElement ||
document.msFullscreenElement;
}
// Full screen mode switching function
function toggleFullscreen() {
if (!isFullscreen()) {
if (targetElement.requestFullscreen) {
targetElement.requestFullscreen();
} else if (targetElement.webkitRequestFullscreen) {
targetElement.webkitRequestFullscreen();
} else if (targetElement.mozRequestFullScreen) {
targetElement.mozRequestFullScreen();
} else if (targetElement.msRequestFullscreen) {
targetElement.msRequestFullscreen();
}
} else {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
}
}
// Bind the click event of the full screen mode switch button
fullscreenButton.addEventListener('click', toggleFullscreen);
// Monitor full screen status changes
document.addEventListener('fullscreenchange', function() {
fullscreenButton.textContent = isFullscreen() ? 'Exit Fullscreen' : 'Toggle Fullscreen';
});
document.addEventListener('webkitfullscreenchange', function() {
fullscreenButton.textContent = isFullscreen() ? 'Exit Fullscreen' : 'Toggle Fullscreen';
});
document.addEventListener('mozfullscreenchange', function() {
fullscreenButton.textContent = isFullscreen() ? 'Exit Fullscreen' : 'Toggle Fullscreen';
});
document.addEventListener('MSFullscreenChange', function() {
fullscreenButton.textContent = isFullscreen() ? 'Exit Fullscreen' : 'Toggle Fullscreen';
});



