簡體   English   中英

在第一個iframe中加載網站,在第二個iframe中加載網站前端代碼

[英]Load website in first Iframe and its front end code in second Iframe

只是為了學習我問這個問題。 我正在使用2個iframe,假設我在Iframe1中加載了一個隨機網站,那么它的前端代碼是否有可能動態/自動顯示在第二個iframe中。 我說的是您在任何網頁上按CTRL + U時看到的代碼。 請幫忙

將任何網站加載到iFrame

您可以執行此操作,但不能對所有網站都執行此操作,這會導致某些網站(例如google和stackoverflow)阻止其加載到框架。

獲取任何網站內容

您無法做到這一點,只有在iframe域與您的網站域相同的情況下才能做到(以下是對策略同源策略的描述)。

您可以做一些修改,這是解決方案

這也是說明相同來源策略例外的小提琴。 使用控制台查看。 小提琴

小提琴代碼

<iframe name="site_frame" id="site_frame" src="http://iherb.com">
</iframe>

<iframe id="code_frame">
    <textarea id="code"></textarea>
</iframe>

document.getElementById('site_frame').onload = function () {    
    console.log("Frame loaded!");
    var siteFrameDoc = getIFrameDocument(document.getElementById('site_frame')),        
        siteFrameHtml = siteFrameDoc.getElementByTagName('html'); 
        wrapper = document.createElement('div');
    wrapper.appendChild(siteFrameHtml.cloneNode(true));


    var codeFrameDoc = getIFrameDocument(document.getElementById('code_frame'));
    var textarea = codeFrameDoc.getElementById("code");
    console.log(textarea);

    textarea.value = wrapper.innerHtml; 
};

function getIFrameDocument(iframe) {      
    return iframe.contentDocument || iframe.contentWindow.document;     
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM