How to style inside an iframe from an external dom

2019-07-17 06:43发布

问题:

I have a website with 3 iframes embedded from 3 different domains. Each iframe is on a separate page. What is the best way to apply a style sheet to all 3 iframes?

Thank you!

回答1:

This can be done with some sites but not all due to "same origin policy". One that does allow it is Twitter. This is the important code.

    $('#iframe').each(function(i){
        var $head = $(this).contents().find('head');
        if ($head.length){
            $head.append($("<link/>", { 
                rel: "stylesheet", 
                href: "http://url.to.your.css", 
                type: "text/css"
            }));
        }
    });

To use the same CSS on more than one page you would use a selector that picks up those three iframes $('#iframe1, #iframe2, #iframe3') but bear in mind one may load slower than another.

It doesn't matter if they are on different pages, the selector will catch whichever exists.

In this following example, which shrinks the default twitter header slightly, setInterval is used to keep checking that the iframe has loaded, and once done it's destroyed.

HTML

<a class="twitter-timeline" style="height:600;" href="#" data-widget-id="your twitter widget id">Tweets</a>

JS

// twitter's own js
    !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");

// jquery to insert the css
$(function(){
    var twitterCssCount = 0;
    var twitterCss=setInterval(function(){
        twitterCssCount++;
        if (twitterCssCount>10) clearTimeout(twitterCss);
        $('iframe.twitter-timeline').each(function(i){
            var $head = $(this).contents().find('head');
            if ($head.length){
                $head.append($("<link/>", { 
                    rel: "stylesheet", 
                    href: "//url.to.your.css", 
                    type: "text/css"
                }));
                clearTimeout(twitterCss);
            }
        });
    },1000);
});

Contents of the CSS file

.stream{
    height:560px !important; /* because we're removing some of the header */
}
.timeline-header{
    padding:0 0 5px 0;
}
.timeline-header .ic-twitter-badge{
    border:0;
    top:7px;
    right:7px;
}
h1.summary, h2.byline{
    display:none !important;
}
p.list-description{
    padding:5px;
    padding-bottom:0;
    margin:0;
}
.root.customisable-border{
    border-color:#666;
    -webkit-border-radius: 0;
    -moz-border-radius: 0;
    border-radius: 0;
}