Sử dụng setTimeout + window.open
<!DOCTYPE html>
<html>
<body>
<script>
setTimeout(myURL, 5000);
function myURL() {
window.open('https://qries.com');
}
</script>
<p>Trang web tải sau 5 giây.</p>
</body>
</html>
Phân biệt: load trong tab hiện tại vs tab mới
| Phương pháp | Hành vi | Dùng khi |
|---|---|---|
window.location.href = url | Tải trong tab hiện tại | Redirect, chuyển trang |
window.location.replace(url) | Tải tab hiện tại, không lưu history | Redirect sau login, tránh Back |
window.open(url) | Mở tab/cửa sổ mới | Link ngoài, popup, quảng cáo |
window.open(url, '_self') | Tải tab hiện tại (giống href) | Ít dùng |
Chặn popup
Trình duyệt thường chặn window.open nếu không phải hành động người dùng trực tiếp (click). Trong ví dụ trên, setTimeout tách biệt sự kiện click → có thể bị chặn.
Giải pháp: Gán setTimeout trong handler click, hoặc dùng location.href.
Ví dụ an toàn (không bị chặn)
<button id="btn">Mở sau 5s</button>
<script>
document.getElementById('btn').addEventListener('click', function() {
setTimeout(function() {
window.open('https://example.com', '_blank');
}, 5000);
});