本文示範如何從外層頁面用 JavaScript 改寫嵌入的 iframe 內容的背景色。
關鍵在於「跨文件存取」:必須先取到 iframe 的 contentWindow 或 contentDocument,再往下鑽到它的 document,才能操作內層的 body。
<!DOCTYPE html> <html> <head> <script> function changeStyle() { var x=document.getElementById("myframe"); var y=(x.contentWindow || x.contentDocument); if (y.document)y=y.document; y.body.style.backgroundColor="#0000ff"; } </script> </head> <body> <iframe id="myframe" src="demo_iframe.htm"> <p>Your browser does not support iframes.</p> </iframe> <br><br> <input type="button" onclick="changeStyle()" value="Change background color"> </body> </html>
那段 (x.contentWindow || x.contentDocument) 就是為了相容不同瀏覽器的差異而寫。另外務必注意:這種跨文件操作只在同一來源(same-origin)下可行。若 iframe 載入的是外部網域,瀏覽器會基於同源政策拋出安全性錯誤,這是瀏覽器的保護機制,無法(也不應該)繞過。
希望本文所述對大家的 JavaScript 程式設計有所幫助。