javascript中有没有办法用getElementsByTagName获取所有不违反同源策略的iframe?

时间:2019-10-25 19:40:12

标签: javascript iframe google-chrome-extension

我正在编写一个Chrome扩展程序,该扩展程序需要在页面上获取html5视频元素,但某些视频元素位于iframe中。我将功能添加到iframe中进行搜索,但是由于与具有不同src域的iframe相关的同源策略,我开始出现错误。

在我的函数中,是否有一种简便的方法来排除违反Same-Origin-Policy的iframe?还是更好(尽管可能不可能),有没有办法从主页上搜索具有不同src域的iframe?

相关功能:

function getVideo() {
    var videos = document.getElementsByTagName("video");
    if (videos.length >= 1) {
        return videos[0];
    }
    var iframes = document.getElementsByTagName("iframe");
    if (iframes.length >= 1) {
        for (const frame of iframes) {
            videos = frame.contentWindow.document.getElementsByTagName("video");
            if (videos.length >= 1) {
                return videos[0];
            }
        }
    }
    return null; // if a video doesn't exist
}

1 个答案:

答案 0 :(得分:0)

当您认为自己在这里进行了足够长时间的搜索以提出问题时,就会发现实际上有用的东西。

基于对this question的回答,我将代码更新为:

const rp = require('request-promise');


var site1 = {
    uri: 'https://www.site1.com/api/v1/somedata.json',
    json: true
};


var site2 = {
    uri: 'https://www.site2.com/api/v1/somedata.json',
    json: true
};

var site3 = {
    uri: 'https://www.site3.com/api/v1/somedata.json',
    json: true
};


var promises = [];
promises.push(rp(site1));
promises.push(rp(site2));
promises.push(rp(site3));


Promise.all(promises).then(data => {
    console.log(data);
    // fetch all data from data variable and do calulation 
}, err => {
    console.log('error')
});

并将其包括在我的清单中,这样脚本也将被注入到iframe中:

function getVideo() {
    var videos = document.getElementsByTagName("video");
    if (videos.length >= 1) {
        return [videos[0], "main"];
    }

    // Code that will run only inside iframe
    if (parent === top) {
        var videos = document.getElementsByTagName("video");
        if (videos.length >= 1) {
            return [videos[0], "iframe"];
        }
    }
    return [null, null]; // if a video doesn't exist
}

这可行,但是确实使我的其他功能很难看。示例:

"content_scripts": [{
    "all_frames": true,
    ...

    ...
}],

我将尝试提出一种更清洁的解决方案,但目前它可以工作。希望这对任何人都有帮助。