Experiment with Window Open and Close Methods
In this step, you'll explore the window.open()
and window.close()
methods, which allow you to programmatically create and manage new browser windows or tabs.
Navigate to the project directory:
cd ~/project/bom-demo
First, create a new HTML file called popup.html
:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Popup Window</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
padding: 20px;
}
</style>
</head>
<body>
<h1>This is a Popup Window</h1>
<p>Opened using window.open() method</p>
<button onclick="window.close()">Close Window</button>
</body>
</html>
Now, update the bom-methods.js
file with window manipulation methods:
// Function to open a new window
function openNewWindow() {
const outputDiv = document.getElementById("output");
// Open a new window with specific dimensions
const newWindow = window.open(
"popup.html",
"PopupWindow",
"width=400,height=300,resizable=yes"
);
// Check if window was successfully opened
if (newWindow) {
outputDiv.textContent = "New window opened successfully!";
} else {
outputDiv.textContent = "Popup blocked. Please allow popups.";
}
}
// Function to close the most recently opened window
function closeLastWindow() {
const outputDiv = document.getElementById("output");
try {
// Attempt to close the last opened window
const lastWindow = window.open("", "_blank");
if (lastWindow) {
lastWindow.close();
outputDiv.textContent = "Last opened window closed.";
} else {
outputDiv.textContent = "No window to close.";
}
} catch (error) {
outputDiv.textContent = "Error closing window.";
}
}
// Create buttons for window operations
function createWindowButtons() {
const openButton = document.createElement("button");
openButton.textContent = "Open New Window";
openButton.onclick = openNewWindow;
const closeButton = document.createElement("button");
closeButton.textContent = "Close Last Window";
closeButton.onclick = closeLastWindow;
document.body.appendChild(openButton);
document.body.appendChild(closeButton);
}
// Call the function to add buttons when page loads
createWindowButtons();
Update the index.html
file to ensure compatibility:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>BOM Methods Demonstration</title>
</head>
<body>
<h1>Browser Object Model (BOM) Methods</h1>
<div id="output"></div>
<script src="bom-methods.js"></script>
</body>
</html>
Key points about window.open()
and window.close()
:
window.open()
creates a new browser window or tab
- Can specify URL, window name, and features
window.close()
closes the current or specified window
- Popup blockers may prevent window opening
When you open the index.html
file in a web browser:
- Click "Open New Window" to create a new popup window
- Click "Close Last Window" to close the recently opened window
- The output div will show the status of window operations