Experimentar com os Métodos de Abrir e Fechar Janela
Nesta etapa, você explorará os métodos window.open() e window.close(), que permitem criar e gerenciar programaticamente novas janelas ou abas do navegador.
Navegue até o diretório do projeto:
cd ~/project/bom-demo
Primeiro, crie um novo arquivo HTML chamado 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>
Agora, atualize o arquivo bom-methods.js com os métodos de manipulação de janela:
// 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();
Atualize o arquivo index.html para garantir a compatibilidade:
<!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>
Pontos-chave sobre window.open() e window.close():
window.open() cria uma nova janela ou aba do navegador
- Pode especificar URL, nome da janela e recursos
window.close() fecha a janela atual ou especificada
- Bloqueadores de pop-up podem impedir a abertura de janelas
Ao abrir o arquivo index.html em um navegador web:
- Clique em "Open New Window" para criar uma nova janela pop-up
- Clique em "Close Last Window" para fechar a janela aberta recentemente
- A div de saída mostrará o status das operações da janela