我們將在本教程中學(xué)習(xí)使用 JavaScript 關(guān)閉瀏覽器窗口。假設(shè)用戶在 2 個(gè)選項(xiàng)卡中打開了您的網(wǎng)站并且不想允許它,那么您可以使用 JavaScript 自動(dòng)關(guān)閉一個(gè)選項(xiàng)卡。
此外,如果您注意到某些網(wǎng)絡(luò)應(yīng)用程序會(huì)自動(dòng)打開瀏覽器窗口來(lái)捕獲臉部,那么當(dāng)您通過(guò)單擊按鈕捕獲圖像時(shí),它會(huì)自動(dòng)關(guān)閉。這就是我們使用 JavaScript 所能做的一切。
本教程將教授使用 JavaScript 關(guān)閉瀏覽器窗口中當(dāng)前選項(xiàng)卡的不同示例。
注意 – JavaScript 永遠(yuǎn)不允許開發(fā)人員關(guān)閉用戶打開的窗口。這是由于一些安全問(wèn)題。所以,程序員只能關(guān)閉使用JavaScript的open()方法打開的瀏覽器窗口。
語(yǔ)法
您可以按照以下語(yǔ)法使用close()方法關(guān)閉瀏覽器窗口。
let new_window = window.open(URL, width, height); new_window.close();
登錄后復(fù)制
在上面的語(yǔ)法中,我們?cè)趧?chuàng)建 new_window 變量時(shí)將返回值存儲(chǔ)在其中。之后,我們使用 close() 方法關(guān)閉新打開的窗口。
示例
在這個(gè)例子中,我們有兩個(gè)按鈕;一種是打開新選項(xiàng)卡,另一種是關(guān)閉使用 JavaScript 打開的新選項(xiàng)卡。
用戶首先需要通過(guò)單擊“打開新選項(xiàng)卡”按鈕使用 JavaScript 打開選項(xiàng)卡。他們可以單擊“關(guān)閉新選項(xiàng)卡”按鈕后,觀察它會(huì)自動(dòng)關(guān)閉該選項(xiàng)卡。
<html>
<body>
<h2>Using the <i>window.close()</i> method to close the browser's tab</h2>
<p>Click "Open New Tab" to open a page in new tab and click "Close New Tab" to colse the opened tab</p>
<button id = "openTab" onclick = "openTab()">Open New Tab </button><br><br>
<button id = "closeTab" onclick = "closeTab()">Close New Tab</button>
<script>
// creating the variable to store the tab
var new_tab;
function openTab() {
// open a new tab
new_tab = window.open("https://www.tutorialspoint.com/answers/shubham-vora");
}
function closeTab() {
// close tab
new_tab.close();
}
</script>
</body>
</html>
登錄后復(fù)制
示例
在下面的示例中,我們創(chuàng)建了兩個(gè)按鈕,如上面的示例,用于打開和關(guān)閉選項(xiàng)卡。但是,在本示例中,我們還添加了“_blank”作為 open 方法的參數(shù),這將打開一個(gè)新窗口而不是新選項(xiàng)卡。
接下來(lái),用戶可以單擊新窗口按鈕來(lái)關(guān)閉彈出窗口。
<html>
<body>
<h2>Using the <i>window.close() method</i> to close the browser's window.</h2>
<p>Click "Open New Window" to open the page in new window and click "Close New Window" to colse the opened window</p>
<button id = "openWidnow" onclick = "openWindow()"> open new Window</button><br><br>
<button id = "closeWidnow" onclick = "closeWindow()">Close new Window</button>
<script>
// creating the variable to store window
var new_window;
function openWindow() {
// open a new window
new_window = window.open("https://www.tutorialspoint.com/index.htm", "_blank", "width=800");
}
function closeWindow() {
// close the window
new_window.close();
}
</script>
</body>
</html>
登錄后復(fù)制
因此,用戶學(xué)習(xí)使用 JavaScript 打開新選項(xiàng)卡或窗口。此外,還學(xué)習(xí)了使用 close() 方法關(guān)閉選項(xiàng)卡或窗口。
此外,我們還可以打開新窗口來(lái)接受用戶輸入,當(dāng)用戶提交表單數(shù)據(jù)時(shí),我們可以在處理表單數(shù)據(jù)的函數(shù)中調(diào)用 close() 方法。
以上就是如何使用 JavaScript 關(guān)閉瀏覽器窗口中的當(dāng)前選項(xiàng)卡?的詳細(xì)內(nèi)容,更多請(qǐng)關(guān)注www.92cms.cn其它相關(guān)文章!






