Override body style for content in an iframe

前端 未结 10 943
青春惊慌失措
青春惊慌失措 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: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.

提交回复
热议问题