Tampermonkey JavaScript jQuery how to find and edit elements of an embedded web page?

How to access a web page after having embedded it into a div? Trying normally just returns null. Here's an example of what I mean:

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/

Upvotes: 2

Views: 1729

Answers (1)

keja
keja

Reputation: 1363

You would have to wait for the content to load and then access the content, i have made a small update to your fiddle, it does not work in there due to cross-origin.

HTML:

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

JS:

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/

but should work if you load something from the same domain.

Upvotes: 1

Related Questions