瀏覽器同源策略禁止直接操作不同頁面的 DOM。a.html 無法直接在 b.html 建立 <div>。
// a.html 按鈕點擊
document.getElementById('btn').onclick = function() {
location.href = 'b.html?createDiv=1'; // 攜帶指令參數
};
// b.html 載入時檢查
window.onload = function() {
const params = new URLSearchParams(location.search);
if (params.get('createDiv') === '1') {
const div = document.createElement('div');
div.textContent = '從 a.html 建立';
document.body.appendChild(div);
}
};
// a.html
localStorage.setItem('action', 'createDiv');
location.href = 'b.html';
// b.html
window.addEventListener('storage', function(e) { // 同源不同頁面同步
if (e.key === 'action' && e.newValue === 'createDiv') {
createDiv();
}
});
// 或直接 onload 讀取
if (localStorage.getItem('action') === 'createDiv') {
createDiv();
localStorage.removeItem('action'); // 執行一次清除
}
// 適用於多標籤頁即時同步
const channel = new BroadcastChannel('app-channel');
channel.postMessage({type: 'CREATE_DIV'});
// 接收端
channel.onmessage = (e) => {
if (e.data.type === 'CREATE_DIV') createDiv();
};
| 場景 | 推薦方案 |
|---|---|
| 單次跳轉帶參數 | URLSearchParams |
| 需持久化/多頁面共享狀態 | localStorage |
| 多標籤頁即時通訊 | BroadcastChannel |