【问题标题】:Tampermonkey JavaScript jQuery how to find and edit elements of an embedded web page?Tampermonkey JavaScript jQuery 如何查找和编辑嵌入网页的元素?
【发布时间】:2017-09-06 09:53:38
【问题描述】:

如何在将网页嵌入到 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/

【问题讨论】:

  • @是否来自同一个域?我的意思是,您嵌入的网站属于同一个域??
  • 是的,它来自同一个域。
  • 据我了解,如果它属于同一个域,那么您可以使用 iframe 代替对象,然后尝试console.log($(".div1 iframe").contents().find("html").html());。让我知道它是否有效??
  • 我收到“VM8873:53 Uncaught TypeError: ".div1 iframe".contents is not a function at window.onload”。我认为它被解释为文本。
  • 你用 iframe 代替了 object 吗?我认为您正在 jsfiddle 中对其进行测试。将此应用到您自己的应用程序中。

标签: javascript jquery google-chrome embedding tampermonkey


【解决方案1】:

你必须等待内容加载然后访问内容,我对你的小提琴做了一个小更新,由于跨域,它在那里不起作用。

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/

但是如果你从同一个域加载一些东西应该可以工作。

【讨论】:

  • 谢谢,它有效。有没有办法让它等到内容加载而不设置任意时间延迟?
  • 一旦 iframe 完成加载,承诺上面的代码就会被解析。
  • 看起来没有超时,文档部分在[Violation] 'setTimeout' handler took 59ms[Violation] Forced reflow while executing JavaScript took 82ms 之间运行。有没有办法跟踪它们并在它们之后运行一些东西?
  • 您可以使用MutationObserver 并在它检测到您要查找的元素在 DOM 中时执行一些代码。
  • 我以为我想通了,我将 iframe.onload 更改为 document.ready 用于解析功能,但现在它有时有效,有时无效。
猜你喜欢
  • 1970-01-01
  • 2021-09-25
  • 2018-10-03
  • 2013-10-13
  • 2014-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多