如何在 JavaScript 中獲取 iframe 的內容?
我們使用 getIframeContent(frameId) 在 JavaScript 中獲取 iframe 的物件引用。
要獲取 iframe 中的元素,首先我們需要使用 document.getElementById() 方法透過傳遞 iframe id 作為引數來訪問 JavaScript 中的 <iframe> 元素。
使用 iframe 標籤
HTML 中的 <iframe> 標籤指定了一個內聯框架。此內聯框架用於在當前 HTML 文件中嵌入另一個文件。
<iframe> 元素在每個瀏覽器中都受支援,例如(Google Chrome、Microsoft Edge/Internet Explorer、Firefox、Safari 和 Opera)。
我們在 <iframe> 標籤中使用 srcdoc 屬性來指定要在 <iframe> 中顯示的頁面 HTML 內容。
srcdoc 屬性將 HTML_code 作為值,並指定要在 <iframe> 中顯示的頁面 HTML 內容。
以下是在 HTML 中使用 <iframe> 標籤和 srcdoc 屬性指定要在 <iframe> 中顯示的頁面 HTML 內容的示例。
現在讓我們逐一檢視這些示例。
示例
以下是用 iframe 建立視窗的示例程式。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <iframe id = "myId" name = " myId ">...</iframe> <script> var myDoc; if (window.frames && window.frames. myId && (myDoc = window.frames. myId.document)) { var iframeBody = myDoc.body; var content = iframeBody.innerHTML; } </script> </body> </html>
示例
以下是在 iframe 建立的視窗上放置內容的示例程式。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title> How to get HTML content of an iFrame using javascript? </title> </head> <body> <iframe id="frameID" src="Untitled-2.html"> </iframe> <a href="#" onclick= "getIframeContent('frameID');"> Get content of Iframe </a> <script> function getIframeContent(frameID) { var frameObj = document.getElementById(frameID); var frameContent = frameObj.contentWindow.document.body.innerHTML; alert("frame content : " + frameContent); } </script> </body> </html>
Undefined.html
<!DOCTYPE html> <html> <body> got the body's content of an iframe in JavaScript </body> </html>
點選“獲取內容”後,將彈出一個視窗顯示 iframe 的內容。
廣告