Override body style for content in an iframe

前端 未结 10 945
青春惊慌失措
青春惊慌失措 2020-11-22 01:10

How can I control the background image and colour of a body element within an iframe? Note, the embedded body element has a class, and the iframe i

相关标签:
10条回答
  • 2020-11-22 01:39

    An iframe has another scope, so you can't access it to style or to change its content with javascript.

    It's basically "another page".

    The only thing you can do is to edit its own CSS, because with your global CSS you can't do anything.

    0 讨论(0)
  • 2020-11-22 01:41

    The below only works if the iframe content is from the same parent domain.

    The following jquery script works for me. Tested on Chrome and IE8. The inner iframe references a page that is on the same domain as the parent page.

    In this particular case, I am hiding an element with a specific class in the inner iframe.

    Basically, you just append a style element to the head section of the document loaded in a frame:

    frame.addEventListener("load", ev =>
        const new_style_element = document.createElement("style");
        new_style_element.textContent = ".my-class { display: none; }"
        ev.target.contentDocument.head.appendChild(new_style_element);
    });
    

    You can also instead of style use a link element, for referencing a stylesheet resource.

    0 讨论(0)
  • 2020-11-22 01:42

    If you have control of the page hosting the iframe and the page of the iframe, you can pass a query parameter to the iframe...

    Here's an example to add a class to the iframe based on whether or not the hosting site is mobile...

    Adding iFrame:

    var isMobile=$("mobile").length; //detect if page is mobile
    var iFrameUrl ="https://myiframesite/?isMobile=" + isMobile; 
    
    $(body).append("<div id='wrapper'><iframe src=''></iframe></div>");
    $("#wrapper iframe").attr("src", iFrameUrl ); 
    

    Inside iFrame:

    //add mobile class if needed
    var url = new URL(window.location.href);
    var isMobile = url.searchParams.get("isMobile");
    if(isMobile == "1") {
        $("body").addClass("mobile");
    }
    
    0 讨论(0)
  • 2020-11-22 01:43

    Perhaps it's changed now, but I have used a separate stylesheet with this element:

    .feedEkList iframe
    {
    max-width: 435px!important;
    width: 435px!important;
    height: 320px!important;
    }
    

    to successfully style embedded youtube iframes...see the blog posts on this page.

    0 讨论(0)
提交回复
热议问题