Css style body in iframe

Override body style for content in an iframe

An iframe is a ‘hole’ in your page that displays another web page inside of it. The contents of the iframe is not in any shape or form part of your parent page.

As others have stated, your options are:

  • give the file that is being loaded in the iframe the necessary CSS
  • if the file in the iframe is from the same domain as your parent, then you can access the DOM of the document in the iframe from the parent.

Solution 2

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.

Solution 3

You cannot change the style of a page displayed in an iframe unless you have direct access and therefore ownership of the source html and/or css files.

Solution 4

This code uses vanilla JavaScript. It creates a new element. It sets the text content of that element to be a string containing the new CSS. And it appends that element directly to the iframe document’s head.

Keep in mind, however, that accessing elements of a document loaded from another origin is not permitted (for security reasons) — contentDocument of the iframe element will evaluate to null when attempted from the browsing context of the page embedding the frame.

var iframe = document.getElementById('the-iframe'); var style = document.createElement('style'); style.textContent = 'body ' ; iframe.contentDocument.head.appendChild(style); 

Solution 5

Override another domain iframe CSS

By using part of SimpleSam5’s answer, I achieved this with a few of Tawk’s chat iframes (their customization interface is fine but I needed further customizations).

In this particular iframe that shows up on mobile devices, I needed to hide the default icon and place one of my background images. I did the following:

Tawk_API.onLoad = function() < // without a specific API, you may try a similar load function // perhaps with a setTimeout to ensure the iframe's content is fully loaded $('#mtawkchat-minified-iframe-element'). contents().find("head").append( $(""+ "#tawkchat-status-text-container "+ "#tawkchat-status-icon ") ); >; 

I do not own any Tawk’s domain and this worked for me, thus you may do this even if it’s not from the same parent domain (despite Jeremy Becker’s comment on Sam’s answer).

Читайте также:  Html style background color red

Accessing an iframe document (contentWindow) - JavaScript Tutorial

How to Inject Custom HTML and CSS into an iFrame

CSS : Override body style for content in an iframe

How to Automatically Resize an iFrame (Using iFrameResize.js)

How to CSS : Override body style for content in an iframe

How to override styling of WordPress content with CSS

jd6699

Comments

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 is of a page that is part of my site. The reason I need this is that my site has a black background assigned to the body, and then a white background assigned to divs that contain text. A WYSIWYG editor uses an iframe to embed content when editing, but it doesn’t include the div, so the text is very hard to read. The body of the iframe when in the editor has a class that isn’t used anywhere else, so I’m assuming this was put there so problems like this could be solved. However, when I apply styles to class.body they don’t override the styles applied to body. The weird thing is that the styles do appear in Firebug, so I’ve no idea what’s going on! Thanks UPDATE — I’ve tried @mikeq’s solution of adding a style to the class that is the body’s class. This doesn’t work when added to the main page’s stylesheet, but it does work when added with Firebug. I’m assuming this is because Firebug is applied to all elements on the page whereas the CSS is not applied within iframes. Does this mean that adding the css after window load with JavaScript would work?

Frank Nocke

While it’s not possible to touch anything in an iframe, loading that URL per Ajax into a

can at times be a workaround (if given CORS-Header are allowing for that). (and „sanitizing“ the loaded data by regexp on the way. Yes, all hacky. )

You can use javascript if the page domains match, but why not just put a style block in your inner page’s HTML to override the colors you want changed? Just add more selectors in your override or use important! if all else fails, to override any color styles you want only on that one page.

@FrankNocke I’ve got your method to work for loading external site content into a

via AJAX. However, how can I style the page better this way?

Frank Nocke

@MichaelYaeger Well, sadly, you have to bring on fresh, new (or duplicated) styles (with the host document, in which you are placing things), likely specifically targeted ( .class , #id ) at that div in which you are loading.

Well then you will need to change the source file on your site (you cannot modify any contents in an iframe) — so if the iframe is pointing at mysite.com/test.html then you will need to modify test.html directly.

This is weird. Your solution works for me when I add it to the page with firebug, but doesn’t work if its in the page’s normal css file. Could this be part of your comment ‘assuming the page within the iFrame is yours to edit’? I didnt understand what you meant by that. Thanks

Читайте также:  Java find file linux

I mean by that, is the page you are loading into the iFrame from your site and under your control? or is it from an external site that you cannot edit the source to include that id/class.

It is from my site, but as its done in by the editor it wont be easy to change the mark up that is pulled through.

ps I didnt mean add the to your main page, but to the page within the iFrame. That way you can target the body of the iFrame page with a different style to your main page. You are also referencing the CSS file in your iFrame pages also aren’t you. You need to treat the page loaded in the iFrame as a completely independant page. If you load just that page into a web browser does it have the correct style?

Im not actually sure where the ‘page’ is as its not the whole page the editor uses. Thanks for your help, I think I understand how all this stuff works noe.

Shaiful Islam

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.

pwdst

This only applies to the iFrame element itself — the question asks specifically about the iFrame content, which it currently isn’t possible to change through CSS alone.

Kamalakannan J

@sincerekamal Here’s the code without the need of jQuery: jsfiddle.net/9g9wkpon You just need to know that hyphenated CSS properties are written in camelCase in JavaScript, like in my example. 🙂

Alex Stanese

jquery.js?ver=1.12.4:2 Uncaught DOMException: Failed to read the ‘contentDocument’ property from ‘HTMLIFrameElement’: Blocked a frame with origin «xxxxxxxxx.com» from accessing a cross-origin frame.

@AlexStanese as jeremy states, this only works if the iframe page is coming from the same server as the parent page. which typically means you don’t need to bother with javascript anyways. just add the CSS to the other page in the f irst place.

@KamalakannanJ you don’t even need to use Javascript. Just edit the page that’s in the iFrame and put the CSS there.

Источник

CSS to iFrame: Как Изменить CSS в iFrame

Добавление CSS стилей на родительской странице не работает для тегов iFrame. Из данного руководства вы узнаете, как с помощью JavaScript изменить CSS стили в iFrame, а также как добавить новые (подключить с помощью link).

Пусть у нас есть iFrame с >

Чтобы добавить новые стили для содержимого iFrame, используем следующий JavaScript код:

window.onload = () => < let iframeName = document.getElementById("iframeName"); let iframeContent = iframeName.contentDocument; iframeContent.body.innerHTML = iframeContent.body.innerHTML + ".iframe-css "; >

Если необходимо добавить в iFrame много CSS стилей, то данный подход не очень удобен. Рассмотрим, как можно подключить новые файлы стилей в теге

Добавление CSS файлов в iFrame

Чтобы добавить новый файл, используем следующий код:

// Добавление css файла в IFRAME window.onload = () => < // создаём новый тег "link" для iFrame и заполняем его "href", "rel" и "type" let iframeLink = document.createElement("link"); iframeLink.href = "fileName.css"; // css файл для iFrame iframeLink.rel = "stylesheet"; iframeLink.type = "text/css"; // вставляем в [0] - индекс iframe frames[0].document.head.appendChild(iframeLink); >
// Вставка CSS в iFrame link $("#iframeName").on("load", () => < let iframeHead = $("#iframeName").contents().find("head"); // находим "head" iFrame let newLink = $("link"); // создаём тег "link" и далее заполняем атрибуты $("link").attr("href", "fileName.css"); $("link").attr("rel", "stylesheet"); $("link").attr("type", "text/css"); $(iframeHead).append(newLink); // вставляем в наш iFrame >);

Таким образом мы создали тег и затем заполнили его атрибуты. Теперь в этом CSS файле вы можете писать все необходимые стили для содержимого iFrame.

Читайте также:  Changing image src in css

Данный способ работает, если iframe находится на вашем домене.

Надеюсь, вам понравилась данная информация. Если вам интересна тема web-разработки, то можете следить за выходом новых статей в Telegram.

Статьи из данной категории:

Комментарии ( 3 )

 // вставляем в [0] - индекс iframe frames[0].document.head.appendChild(iframeLink); 

Здравствуйте! Большое спасибо за статью. Пока не получается повторить. Подскажите пожалуйста, на вот таком примере, как через CSS можно убрать внизу формы надпись «Создано пользователем с помощью. «

Источник

How to Apply CSS to iFrame

adding-css-to-iframe

iFrame is a very convenient way to display an external content on your webpage. However, it’s little bit complicate if you want to add additional or alter the existing CSS style. You cannot simply add CSS on the parent/wrapper page. In this tutorial, we’ll show you how to use JavaScript to inject CSS into iFrame.

In the snippet below, once everything was loaded, we’ll get the iFrame element by ID. Then get the contentDocument and inject our styles into iFrame using innerHTML.

window.onload = function() < let myiFrame = document.getElementById("myiFrame"); let doc = myiFrame.contentDocument; doc.body.innerHTML = doc.body.innerHTML + ''; >

Or you can do it with jQuery.

$("#myiFrame").on("load", function() < let head = $("#myiFrame").contents().find("head"); let css = ''; $(head).append(css); >);

Example

For example, here is the 3D CSS Progressbar tutorial page that we want to add to ours using iframe.

How to add css to iframe

Suppose that we want to change the length of the progress bar to 45%. Unfortunately, we can’t do something like this from our parent CSS.

Let’s try using JavaScript. It’s important that you’ll need to wait until the iFrame was loaded before you can inject the CSS. In this case, we’ll put the code in onload event listener.

window.onload = function() < let frameElement = document.getElementById("myiFrame"); let doc = frameElement.contentDocument; doc.body.innerHTML = doc.body.innerHTML + '.bar '; >

add-css-to-iframe-2

Adding CSS File to iFrame

You can add entire CSS file instead of injecting separated styles by creating link and add it to the iframe’s head.

This method does not work with cross domain content. You’ll need to set appropriate CORS header but it’s not recommended due to security risks.

TK Engineer, Web Developer, Ex-Mutual Funds Software Developer. He founded Red Stapler in 2015 to share useful resources for everyone interested in web design, web development and programming. Subscribe his YouTube Channel or Twitter for weekly tips and tutorials.

Источник

Оцените статью