代码之家  ›  专栏  ›  技术社区  ›  Máté Burján

如何查找和编辑嵌入式网页的元素?

  •  2
  • Máté Burján  · 技术社区  · 7 年前

    如何在将网页嵌入div后访问它?正常尝试只返回null。以下是我的意思示例:

    var replaceThis = document.querySelector('.div1');
    var withThis = document.querySelector('.div2 a').getAttribute("href");
    replaceThis.innerHTML = '<object type="text/html" data="' + withThis + '" style="width: -webkit-fill-available; height: -webkit-fill-available;"></object>';
    
    var thingFromEmbeddedSite = document.querySelector('.div2'); //returns div2
    console.log(thingFromEmbeddedSite);
    
    thingFromEmbeddedSite = document.querySelector('h2'); //returns null
    console.log(thingFromEmbeddedSite);
    

    https://jsfiddle.net/zhhL9rjr/3/

    1 回复  |  直到 7 年前
        1
  •  1
  •   keja    7 年前

    你必须等待内容加载,然后访问内容,我已经对你的fiddle做了一个小更新,由于跨来源,它在那里无法工作。

    <body>
        <div class="div1">
            stuff
        </div>
        <div class="div2">
            <a href="https://jsfiddle.net/user/login/">link</a>
        </div>
    </body>
    

    function embed(src, target){
        return new Promise(function(resolve, reject){
            let iframe = document.createElement("iframe");
            iframe.src = src;
            iframe.style = "width: -webkit-fill-available;height: -webkit-fill-available;";
            iframe.onload = function(){
                resolve(iframe.contentWindow.document);
            };
    
          target.parentNode.replaceChild(iframe, target);
       });
    }
    
    let href = document.querySelector('.div2 a').getAttribute("href"),
        target = document.querySelector('.div1');
    
    embed(href, target).then(function(doc){
    
        console.log( doc.querySelector('h2') );
    
    });
    

    https://jsfiddle.net/zhhL9rjr/6/

    但如果从同一个域加载某些内容,则应该可以正常工作。