Tampermonkey JavaScript jQuery 如何查找和编辑嵌入式网页的元素?
Tampermonkey JavaScript jQuery how to find and edit elements of an embedded web page?
网页嵌入div后如何访问?正常尝试只是 returns 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);
您将不得不等待内容加载然后访问内容,我对您的 fiddle 做了一个小更新,由于跨源,它在那里不起作用。
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/
但如果您从同一域加载内容,应该可以正常工作。
网页嵌入div后如何访问?正常尝试只是 returns 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);
您将不得不等待内容加载然后访问内容,我对您的 fiddle 做了一个小更新,由于跨源,它在那里不起作用。
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/
但如果您从同一域加载内容,应该可以正常工作。