萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

JavaScript 經典特效:主頁遙控器、單次彈窗、Cookie 控制與現代替代方案

前言

原文收錄的「主頁遙控器」、「只彈一次的窗口」屬於早期 Web 開發常見互動模式。現代瀏覽器預設攔截彈窗、用戶體驗優先,本文在保留經典邏輯的同時,提供現代最佳實踐替代方案。

經典特效一:主頁遙控器 (跨視窗通訊)

原理

父視窗 `window.open()` 開啟子視窗,子視窗透過 `window.opener` 存取父視窗 DOM 並導航。

經典實作 (t1.html + t2.html)

<!-- t1.html 父視窗 -->
<script>
function openRemote() {
    // 開啟遙控器視窗
    window.open('t2.html', 'remoteControl', 'width=300,height=400,scrollbars=no,resizable=yes');
}
</script>
<button onclick="openRemote()">開啟遙控器</button>
<!-- t2.html 子視窗 (遙控器) -->
<script>
function navigateParent(url) {
    if (window.opener && !window.opener.closed) {
        try {
            window.opener.location.href = url;
            // 或 window.opener.document.location = url;
        } catch (e) {
            console.error('跨域限制:', e);
            alert('無法控制父視窗:跨域限制');
        }
    } else {
        alert('父視窗已關閉或被攔截');
    }
}
</script>
<button onclick="navigateParent('page1.html')">頁面 1</button><br>
<button onclick="navigateParent('page2.html')">頁面 2</button><br>
<button onclick="navigateParent('https://example.com')">外部網站</button>

現代替代:postMessage 跨域通訊 (安全、標準)

<!-- parent.html -->
<script>
let childWindow = null;
function openRemote() {
    childWindow = window.open('remote.html', 'remote', 'width=300,height=400');
}

// 監聽子視窗訊息
window.addEventListener('message', (event) => {
    // 安全性:驗證來源
    if (event.origin !== 'https://your-trusted-domain.com') return;
    
    if (event.data.type === 'NAVIGATE') {
        window.location.href = event.data.url;
    }
});
</script>
<button onclick="openRemote()">開啟遙控器</button>
<!-- remote.html (子視窗) -->
<script>
function sendNavigate(url) {
    if (window.opener) {
        window.opener.postMessage({
            type: 'NAVIGATE',
            url: url
        }, 'https://parent-domain.com'); // 指定目標 origin
    }
}
</script>
<button onclick="sendNavigate('page1.html')">頁面 1</button>

經典特效二:只彈一次的窗口 (Cookie 控制)

原始邏輯

檢查 Cookie 是否存在 → 不存在則彈窗並寫入 Cookie → 存在則不彈。

原始代碼現代化重寫

<script>
/**
 * 單次彈窗管理器
 * @param {Object} options
 *   - url: 彈窗網址
 *   - name: 視窗名稱
 *   - specs: window.open 規格字串
 *   - cookieName: Cookie 名稱
 *   - expiryDays: Cookie 過期天數
 *   - condition: 額外條件函式 (回傳 true 才彈出)
 */
function openOnce(options) {
    const opts = Object.assign({
        url: 'ad.html',
        name: 'popup',
        specs: 'width=400,height=300,scrollbars=yes,resizable=yes',
        cookieName: 'popup_shown',
        expiryDays: 30,
        condition: () => true
    }, options);
    
    // 檢查 Cookie
    if (getCookie(opts.cookieName)) return;
    if (!opts.condition()) return;
    
    // 開啟彈窗 (可能被攔截)
    const win = window.open(opts.url, opts.name, opts.specs);
    
    // 寫入 Cookie (即使被攔截也記錄,避免反覆嘗試)
    setCookie(opts.cookieName, '1', opts.expiryDays);
    
    return win;
}

/** 設定 Cookie */
function setCookie(name, value, days) {
    const expires = new Date(Date.now() + days * 864e5).toUTCString();
    document.cookie = `${encodeURIComponent(name)}=${encodeURIComponent(value)};expires=${expires};path=/;SameSite=Lax`;
}

/** 讀取 Cookie */
function getCookie(name) {
    const match = document.cookie.match(new RegExp('(^|;\\s*)' + encodeURIComponent(name) + '=([^;]*)'));
    return match ? decodeURIComponent(match[2]) : null;
}

/** 刪除 Cookie (測試用) */
function deleteCookie(name) {
    document.cookie = `${encodeURIComponent(name)}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`;
}

// 使用範例
// 1. 基本用法
openOnce({url: 'promo.html'});

// 2. 進階:僅首次造訪用戶、非行動裝置、非搜尋引擎來路
openOnce({
    url: 'welcome.html',
    cookieName: 'welcome_popup',
    expiryDays: 365,
    condition: () => {
        // 非行動裝置
        if (/Mobi|Android/i.test(navigator.userAgent)) return false;
        // 非搜尋引擎來路 (簡易判斷)
        const ref = document.referrer;
        if (/google|bing|baidu|yahoo|duckduckgo/i.test(ref)) return false;
        return true;
    }
});

現代替代:非阻擋式通知彈窗 (Modal/Toast)

瀏覽器預設攔截 `window.open`,現代做法改用頁面內 Modal:

<!-- HTML -->
<div id="welcomeModal" class="modal hidden" role="dialog" aria-modal="true">
    <div class="modal-content">
        <h2>歡迎來到我們的網站!</h2>
        <p>訂閱電子報獲得 9 折優惠</p>
        <button id="subscribeBtn">立即訂閱</button>
        <button class="modal-close" aria-label="關閉">×</button>
    </div>
</div>

<style>
.modal { position:fixed; inset:0; background:rgba(0,0,0,.5); display:flex; align-items:center; justify-content:center; z-index:1000; }
.modal.hidden { display:none; }
.modal-content { background:#fff; padding:2rem; border-radius:8px; max-width:400px; width:90%; position:relative; }
.modal-close { position:absolute; top:8px; right:12px; background:none; border:none; font-size:1.5rem; cursor:pointer; }
</style>

<script>
function showWelcomeModal() {
    if (localStorage.getItem('welcomeShown')) return;
    if (window.innerWidth < 600) return; // 行動裝置不顯示
    
    const modal = document.getElementById('welcomeModal');
    modal.classList.remove('hidden');
    
    document.getElementById('subscribeBtn').onclick = () => {
        // 訂閱邏輯
        hideModal();
    };
    modal.querySelector('.modal-close').onclick = hideModal;
    modal.onclick = e => e.target === modal && hideModal(); // 點背景關閉
    
    function hideModal() {
        modal.classList.add('hidden');
        localStorage.setItem('welcomeShown', '1');
    }
}

// 頁面載入後延遲顯示
window.addEventListener('load', () => setTimeout(showWelcomeModal, 2000));

Cookie / LocalStorage / SessionStorage 比較

特性CookieLocalStorageSessionStorage
容量4 KB5-10 MB5-10 MB
過期手動設定永久 (手動清除)分頁關閉即清除
自動送至伺服器是 (每請求)否否
跨分頁共享是是否
適用場景身分驗證、追蹤用戶偏好、快取、單次彈窗記錄暫存表單、分頁獨立狀態

現代最佳實踐建議

  1. 避免 window.open:瀏覽器預設攔截,改用頁面內 Modal/Toast/Slide-in
  2. 使用 LocalStorage 記錄狀態:容量大、不隨請求發送、API 簡單
  3. 尊重用戶意願:提供「不再顯示」選項、遵循 GDPR 同意機制
  4. 時機選擇:頁面載入完成、滾動深度 50%、停留 30 秒、離開意圖 (滑鼠移出視窗)
  5. 頻率控制:同一用戶 30 天內最多 1 次、每會話最多 1 次

總結

經典的「主頁遙控器」展示了 `window.opener` 跨視窗操作,但受限於同源政策;「單次彈窗」展示了 Cookie 狀態記憶。現代開發應棄用彈窗,改用頁面內非阻擋式 UI,搭配 localStorage 狀態管理,並透過 postMessage 實現安全跨域通訊。

copyright © 萬盛學電腦網 all rights reserved