// 1. 取得 iframe 的 window 物件
var iframeWin = document.getElementById('myIframe').contentWindow;
// 2. 滾動到指定座標
iframeWin.scrollTo(x, y); // 現代標準 (支援選項物件)
iframeWin.scroll(x, y); // 別名,相容舊瀏覽器
// 3. 取得 iframe 文檔高度 (需同源)
var doc = iframeWin.document;
var fullHeight = doc.documentElement.scrollHeight; // 整份文檔高度
跨域 iframe 無法存取 contentWindow / contentDocument,會拋出 SecurityError。
postMessage 通訊、document.domain 降級 (僅同主域)、代理伺服器、CORS + sandbox="allow-same-origin allow-scripts"。<button id="scrollBottomBtn">滾動到底部</button>
<iframe id="contentFrame" src="long-page.html" width="100%" height="500"></iframe>
<script>
document.getElementById('scrollBottomBtn').addEventListener('click', function() {
var iframe = document.getElementById('contentFrame');
try {
var iwin = iframe.contentWindow;
var doc = iwin.document;
// 滾動到底部 (平滑動畫)
iwin.scrollTo({
top: doc.documentElement.scrollHeight,
behavior: 'smooth'
});
} catch (err) {
console.error('跨域或 iframe 未就緒:', err);
// 降級:請求 iframe 內部自行滾動 (需 postMessage 協作)
}
});
</script>
var iframe = document.getElementById('contentFrame');
iframe.addEventListener('load', function() {
var iwin = iframe.contentWindow;
iwin.addEventListener('scroll', function() {
var scrollTop = iwin.pageYOffset || iwin.document.documentElement.scrollTop;
var scrollHeight = iwin.document.documentElement.scrollHeight;
var clientHeight = iwin.innerHeight;
var percent = scrollTop / (scrollHeight - clientHeight);
console.log('iframe 滾動進度:', Math.round(percent * 100) + '%');
// 父頁面同步顯示進度條、觸發懶載入等
});
});
var iframe = document.getElementById('crossDomainFrame');
iframe.addEventListener('load', function() {
// 發送指令讓 iframe 滾動
iframe.contentWindow.postMessage({ action: 'scrollToBottom' }, '*'); // 生產環境指定具體 origin
});
window.addEventListener('message', function(e) {
if (e.data.type === 'scrollProgress') {
updateProgressBar(e.data.percent);
}
});
window.addEventListener('message', function(e) {
if (e.data.action === 'scrollToBottom') {
window.scrollTo({ top: document.documentElement.scrollHeight, behavior: 'smooth' });
}
});
// 主動回報滾動進度 (節流)
var ticking = false;
window.addEventListener('scroll', function() {
if (ticking) return;
ticking = true;
requestAnimationFrame(function() {
var percent = window.pageYOffset / (document.documentElement.scrollHeight - window.innerHeight);
parent.postMessage({ type: 'scrollProgress', percent: percent }, '*'); // 生產環境指定 parent origin
ticking = false;
});
});
| 問題 | 原因 | 解決 |
|---|---|---|
contentWindow 為 null | iframe 尚未載入完成 | 監聽 iframe.onload 後再操作 |
| SecurityError | 跨域存取 | postMessage 協作、同源部署、document.domain 降級 |
| 滾動無效 | iframe 高度未撐開、CSS overflow 隱藏 | 檢查 iframe 高度、內頁 body/html overflow 設定 |
| scrollTo 平滑動畫不生效 | 舊瀏覽器不支援 behavior 選項 | Polyfill 或用 requestAnimationFrame 手動插值 |
postMessage 會增加主執行緒負擔,滾動回報請 **節流 (throttle) / requestAnimationFrame**。scrollTop) 比 scrollTo 略快,但無動畫。