เปิดหน้าต่าง()
ตัวอย่าง 1
เปิด "www.w3schools.com" ในแท็บเบราว์เซอร์ใหม่:
window.open("https://www.w3schools.com");
ตัวอย่างเพิ่มเติมด้านล่าง
ความหมายและการใช้งาน
วิธี การopen()
นี้จะเปิดหน้าต่างเบราว์เซอร์ใหม่หรือแท็บใหม่ ทั้งนี้ขึ้นอยู่กับการตั้งค่าเบราว์เซอร์ของคุณและค่าพารามิเตอร์
ดูสิ่งนี้ด้วย:
ไวยากรณ์
window.open(URL, name, specs, replace)
พารามิเตอร์
Parameter | Description | ||||||||||||||||||||||||
URL | Optional. The URL of the page to open. If no URL is specified, a new blank window/tab is opened |
||||||||||||||||||||||||
name | Optional. The target attribute or the name of the window. The following values are supported: | ||||||||||||||||||||||||
|
|||||||||||||||||||||||||
specs | Optional. A comma-separated list of items, no whitespaces. The following values are supported: | ||||||||||||||||||||||||
| |||||||||||||||||||||||||
replace |
DeprecatedSpecifies whether the URL creates a new entry or replaces the current entry in the history list. The following values are supported:
WarningChrome throws an exception when using this parameter. Source: . |
คืนมูลค่า
การอ้างอิงถึงหน้าต่างใหม่ หรือnullหากการโทรล้มเหลว |
ตัวอย่างเพิ่มเติม
เปิดหน้า about:blank ในหน้าต่าง/แท็บใหม่:
var myWindow = window.open("", "", "width=200,height=100");
เปิดหน้าต่างใหม่ชื่อ "MsgWindow" และเขียนข้อความลงไป:
var myWindow = window.open("", "MsgWindow", "width=200,height=100");
myWindow.document.write("<p>This is 'MsgWindow'. I am 200px wide and 100px tall!</p>");
แทนที่หน้าต่างปัจจุบันด้วยหน้าต่างใหม่:
var myWindow = window.open("", "_self");
myWindow.document.write("<p>I replaced the current window.</p>");
เปิดหน้าต่างใหม่และควบคุมลักษณะที่ปรากฏ:
window.open("https://www.w3schools.com", "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400");
เปิดหลายแท็บ:
window.open("http://www.google.com/");
window.open("https://www.w3schools.com/");
เปิดหน้าต่างใหม่ ใช้ close() เพื่อปิดหน้าต่างใหม่:
function openWin() {
myWindow = window.open("", "myWindow", "width=200,height=100"); // Opens a new window
}
function closeWin() {
myWindow.close(); // Closes the new window
}
เปิดหน้าต่างใหม่ ใช้คุณสมบัติชื่อเพื่อส่งคืนชื่อของหน้าต่างใหม่:
var myWindow = window.open("", "MsgWindow", "width=200,height=100");
myWindow.document.write("<p>This window's name is: " + myWindow.name + "</p>");
การใช้คุณสมบัติ opener เพื่อส่งคืนการอ้างอิงไปยังหน้าต่างที่สร้างหน้าต่างใหม่:
var myWindow = window.open("", "myWindow", "width=200,height=100"); // Opens a new window
myWindow.document.write("<p>This is 'myWindow'</p>"); // Text in the new window
myWindow.opener.document.write("<p>This is the source window!</p>"); // Text in the window that created the new window
รองรับเบราว์เซอร์
open()
รองรับในทุกเบราว์เซอร์:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |