window.open() 除了單純開啟新視窗外,還有個常被忽略的實用技巧:透過指定「視窗名稱」這個第二參數,可以讓多次點擊重用同一個分頁,而不會每次都不斷彈出新的視窗。以下範例就示範了這個用法。
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
/* 開啟同一個新頁面,不會再次開啟新頁面 */
function open1(){
window.open("html01.html", "aaa");
}
function open2(){
window.open("html02.html", "aaa");
}
</script>
</head>
<body>
<a href="#" onclick="open1()">點擊進入1</a>
<a href="#" onclick="open2()">點擊進入2</a>
</body>
</html>
關鍵就在於兩個函式都傳入了相同的視窗名稱 "aaa"。第一次點擊「點擊進入1」時,會開啟名為 aaa 的視窗並載入 html01.html;接著點擊「點擊進入2」時,由於名稱相同,瀏覽器不會另開新視窗,而是直接把 aaa 視窗的內容導向 html02.html。這個特性在需要讓多個連結共用同一個彈出視窗、避免視窗氾濫時特別好用。