เมธอด replace() ของ Location ใช้โหลดเอกสารใหม่แทนเอกสารปัจจุบัน และลบ URL ปัจจุบันออกจากประวัติ (history) ทำให้ไม่สามารถกดปุ่ม "Back" กลับมาได้
ไวยากรณ์ (Syntax)
location.replace(URLString)
ตัวอย่างการใช้งาน
ตัวอย่างด้านล่างเปลี่ยนหน้าไปยัง URL ใหม่ที่ผู้ใช้ระบุ:
<!DOCTYPE html>
<html>
<head>
<title>Location replace()</title>
<style>
form { width: 70%; margin: 0 auto; text-align: center; }
* { padding: 2px; margin: 5px; }
input[type="button"] { border-radius: 10px; }
</style>
</head>
<body>
<form>
<fieldset>
<legend>Location-replace()</legend>
<label for="urlSelect">Current URL: </label>
<input type="url" id="urlSelect" value="https://www.example.com"><br>
<label for="newUrlSelect">New URL: </label>
<input type="url" id="newUrlSelect" placeholder="Give new url..."><br>
<input type="button" onclick="doReplace()" value="Go to new URL">
<div id="divDisplay"></div>
</fieldset>
</form>
<script>
var divDisplay = document.getElementById("divDisplay");
var urlSelect = document.getElementById("urlSelect");
var newUrlSelect = document.getElementById("newUrlSelect");
function doReplace() {
if(newUrlSelect.value === '')
divDisplay.textContent = 'Provide new URL';
else {
location.replace(newUrlSelect.value);
divDisplay.textContent = 'Redirecting to new URL';
}
}
</script>
</body>
</html>
ผลลัพธ์
คลิก "Go to new URL" โดยไม่กรอก URL: แสดง "Provide new URL"
กรอก URL แล้วคลิก "Go to new URL": ไปหน้าใหม่ทันที ไม่มีใน history (กด Back ไม่ได้)
หมายเหตุ: รูปภาพตัวอย่างจากต้นฉบับไม่ได้รวมอยู่ในเนื้อหานี้
💡 ความแตกต่างจาก location.href: location.href เพิ่มเข้า history (กด Back ได้) ส่วน location.replace() ไม่เพิ่มเข้า history