【问题标题】:Getting html from cross domain iframe window从跨域 iframe 窗口获取 html
【发布时间】:2019-02-22 11:07:56
【问题描述】:

我的索引文件中有一个 iframe,我想从 iframe 中获取所有 html 并将其存储在一个变量中。 iframe 中加载的内容来自另一个域。所以我正在尝试使用 javascript 和 postMessage 以及 eventListener 来实现这一点。到目前为止,这是我的代码。我有一个调用 click 方法的按钮。

index.vue

    click() {
        let iframe = document.getElementById('the_iframe');
        iframe.contentWindow.postMessage('Dont really know what to send here', '*');
        this.test();
    },
    test() {
        window.addEventListener('message', function(event) {
            //Just a test, as the it wont go in the else
            console.log(event.currentTarget.document);
            if (event.origin !== 'http://testdomain') {
                console.log('ERROR');
            } else {
                console.log(event.currentTarget.document);
                const html = event.currentTarget.document); 
                //This however doesnt work. The value is not stored in the const
                console.log(event.currentTarget.document);
            }
        });
    }

当我在控制台记录 event.currentTarget.document 时,它会打印出站点的整个 html 结构,包括父页面(索引)。我的问题是:如何获取索引文件中 iframe 的所有 html?以及如何将其存储在变量中?

【问题讨论】:

标签: javascript html iframe


【解决方案1】:

window.addEventListener('message', 代码需要出现在 文档中。

它需要自动运行。它不应该在函数内部。

(你可以把它放在一个函数中,但它仍然需要先运行,在这种情况下没有理由这样做)。


postMessage 的调用需要是文档中框架内中的脚本,并且它需要将您想要的数据发布给父级。

例如

window.parent.postMessage({ html: document.body.innerHTML }, '*');

现在,如果您想触发获取 HTML 以响应点击事件,那么两个文档都需要 window.addEventListener('message',postMessage 调用:

  1. 父窗口有一个消息侦听器,用于侦听其中包含 HTML 的消息
  2. 父窗口有一个单击事件处理程序,它调用iframe.contentWindow.postMessage 并请求 HTML
  3. Iframe 文档有一个消息侦听器,它侦听带有 HTML 请求的消息,然后调用 window.parent.postMessage({ html: document.body.innerHTML }, '*');

【讨论】:

  • Event.data 正在打印出 [Object object]。当我尝试解析时,我变得不确定?如何打印出来?
  • @Jonathan — 这是一个对象。不要将其转换为字符串。使用console.log 检查其结构。
  • 我试过了。那就是它说[对象对象]的时候。这是代码。 index.vue:click() { 让 iframe = document.getElementById('iframe'); iframe.contentWindow.postMessage('html', '*');},
猜你喜欢
  • 2012-04-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-05
  • 1970-01-01
  • 2013-03-13
相关资源
最近更新 更多