HTML CSS JS
CSS to iFrame: Как Изменить CSS в iFrame
Дата размещения статьи 03/10/2019 👁16816
CSS to iFrame: Как Изменить CSS в iFrame
Добавление CSS стилей на родительской странице не работает для тегов iFrame. Из данного руководства вы узнаете, как с помощью JavaScript изменить CSS стили в iFrame, а также как добавить новые (подключить с помощью link).
Пусть у нас есть iFrame с id = «iframeName».
<iframe id="iframeName" src="./iframe.html"></iframe>
Чтобы добавить новые стили для содержимого iFrame, используем следующий JavaScript код:
window.onload = () => {
let iframeName = document.getElementById("iframeName");
let iframeContent = iframeName.contentDocument;
iframeContent.body.innerHTML = iframeContent.body.innerHTML + "<style>.iframe-css{color: #d92909}</style>";
}
Используя jQuery:
$("#iframeName").on("load", () => {
let iframeHead = $("#iframeName").contents().find("head");
let iframeCSS = "<style>.iframe-css{color: #e91905}</style>";
$(iframeHead).append(iframeCSS);
});
Если необходимо добавить в iFrame много CSS стилей, то данный подход не очень удобен. Рассмотрим, как можно подключить новые файлы стилей в теге <head>
Добавление 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);
}
С помощью jQuery:
// Вставка 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
});
Таким образом мы создали тег <link> и затем заполнили его атрибуты. Теперь в этом CSS файле вы можете писать все необходимые стили для содержимого iFrame.
Данный способ работает, если iframe находится на вашем домене.
Клик вне элемента (блока) Яндекс Метрика API: Счётчик Просмотров
Надеюсь, вам понравилась данная информация. Если вам интересна тема web-разработки,
то можете следить за выходом новых статей в Telegram.
- JavaScript: Работа с Массивами
- Наличие Динамически Добавленного Элемента
- Стилизация Input File
- Предзагрузка Картинок — Предварительная Загрузка Изображений на JavaScript
- Стилизация Скролла
- События Формы
Asked
14 years, 3 months ago
Viewed
1.5m times
I have a simple page that has some iframe sections (to display RSS links). How can I apply the same CSS format from the main page to the page displayed in the iframe?
asked Oct 20, 2008 at 8:27
4
Edit: This does not work cross domain unless the appropriate CORS header is set.
There are two different things here: the style of the iframe block and the style of the page embedded in the iframe. You can set the style of the iframe block the usual way:
<iframe name="iframe1" id="iframe1" src="empty.htm"
frameborder="0" border="0" cellspacing="0"
style="border-style: none;width: 100%; height: 120px;"></iframe>
The style of the page embedded in the iframe must be either set by including it in the child page:
<link type="text/css" rel="Stylesheet" href="Style/simple.css" />
Or it can be loaded from the parent page with Javascript:
var cssLink = document.createElement("link");
cssLink.href = "style.css";
cssLink.rel = "stylesheet";
cssLink.type = "text/css";
frames['iframe1'].document.head.appendChild(cssLink);
brauliobo
5,5464 gold badges28 silver badges33 bronze badges
answered Oct 20, 2008 at 9:07
Tamas CzinegeTamas Czinege
117k40 gold badges148 silver badges175 bronze badges
5
I met this issue with Google Calendar. I wanted to style it on a darker background and change font.
Luckily, the URL from the embed code had no restriction on direct access, so by using PHP function file_get_contents
it is possible to get the
entire content from the page. Instead of calling the Google URL, it is possible to call a php file located on your server, ex. google.php
, which will contain the original content with modifications:
$content = file_get_contents('https://www.google.com/calendar/embed?src=%23contacts%40group.v.calendar.google.com&ctz=America/Montreal');
Adding the path to your stylesheet:
$content = str_replace('</head>','<link rel="stylesheet" href="http://www.yourwebsiteurl.com/google.css" /></head>', $content);
(This will place your stylesheet last just before the head
end tag.)
Specify the base url form the original url in case css and js are called relatively:
$content = str_replace('</title>','</title><base href="https://www.google.com/calendar/" />', $content);
The final google.php
file should look like this:
<?php
$content = file_get_contents('https://www.google.com/calendar/embed?src=%23contacts%40group.v.calendar.google.com&ctz=America/Montreal');
$content = str_replace('</title>','</title><base href="https://www.google.com/calendar/" />', $content);
$content = str_replace('</head>','<link rel="stylesheet" href="http://www.yourwebsiteurl.com/google.css" /></head>', $content);
echo $content;
Then you change the iframe
embed code to:
<iframe src="http://www.yourwebsiteurl.com/google.php" style="border: 0" width="800" height="600" frameborder="0" scrolling="no"></iframe>
Good luck!
Krish Munot
1,0632 gold badges18 silver badges28 bronze badges
answered Sep 20, 2012 at 22:21
4
If the content of the iframe is not completely under your control or you want to access the content from different pages with different styles you could try manipulating it using JavaScript.
var frm = frames['frame'].document;
var otherhead = frm.getElementsByTagName("head")[0];
var link = frm.createElement("link");
link.setAttribute("rel", "stylesheet");
link.setAttribute("type", "text/css");
link.setAttribute("href", "style.css");
otherhead.appendChild(link);
Note that depending on what browser you use this might only work on pages served from the same domain.
niccord
7444 silver badges20 bronze badges
answered Oct 20, 2008 at 8:58
Horst GutmannHorst Gutmann
10.8k2 gold badges26 silver badges31 bronze badges
5
var $head = $("#eFormIFrame").contents().find("head");
$head.append($("<link/>", {
rel: "stylesheet",
href: url,
type: "text/css"
}));
answered Nov 21, 2012 at 16:17
0
Here is how to apply CSS code directly without using <link>
to load an extra stylesheet.
var head = jQuery("#iframe").contents().find("head");
var css = '<style type="text/css">' +
'#banner{display:none}; ' +
'</style>';
jQuery(head).append(css);
This hides the banner in the iframe page. Thank you for your suggestions!
answered Oct 15, 2013 at 22:47
domihdomih
1,37016 silver badges19 bronze badges
0
If you control the page in the iframe, as hangy said, the easiest approach is to create a shared CSS file with common styles, then just link to it from your html pages.
Otherwise it is unlikely you will be able to dynamically change the style of a page from an external page in your iframe. This is because browsers have tightened the security on cross frame dom scripting due to possible misuse for spoofing and other hacks.
This tutorial may provide you with more information on scripting iframes in general. About cross frame scripting explains the security restrictions from the IE perspective.
answered Oct 20, 2008 at 8:52
AshAsh
60.3k31 gold badges151 silver badges168 bronze badges
An iframe is universally handled like a different HTML page by most browsers. If you want to apply the same stylesheet to the content of the iframe, just reference it from the pages used in there.
answered Oct 20, 2008 at 8:37
hangyhangy
10.7k6 gold badges45 silver badges63 bronze badges
1
The above with a little change works:
var cssLink = document.createElement("link")
cssLink.href = "pFstylesEditor.css";
cssLink.rel = "stylesheet";
cssLink.type = "text/css";
//Instead of this
//frames['frame1'].document.body.appendChild(cssLink);
//Do this
var doc=document.getElementById("edit").contentWindow.document;
//If you are doing any dynamic writing do that first
doc.open();
doc.write(myData);
doc.close();
//Then append child
doc.body.appendChild(cssLink);
Works fine with ff3 and ie8 at least
Eric
6,5465 gold badges43 silver badges65 bronze badges
answered Jul 28, 2009 at 22:53
0
The following worked for me.
var iframe = top.frames[name].document;
var css = '' +
'<style type="text/css">' +
'body{margin:0;padding:0;background:transparent}' +
'</style>';
iframe.open();
iframe.write(css);
iframe.close();
answered May 23, 2011 at 16:22
peterpeter
1591 silver badge2 bronze badges
0
Expanding on the above jQuery solution to cope with any delays in loading the frame contents.
$('iframe').each(function(){
function injectCSS(){
$iframe.contents().find('head').append(
$('<link/>', { rel: 'stylesheet', href: 'iframe.css', type: 'text/css' })
);
}
var $iframe = $(this);
$iframe.on('load', injectCSS);
injectCSS();
});
answered Jun 24, 2013 at 11:14
David BradshawDavid Bradshaw
11.6k3 gold badges39 silver badges67 bronze badges
0
use can try this:
$('iframe').load( function() {
$('iframe').contents().find("head")
.append($("<style type='text/css'> .my-class{display:none;} </style>"));
});
answered Sep 1, 2017 at 10:15
TherichpostTherichpost
1,7312 gold badges14 silver badges19 bronze badges
1
If you want to reuse CSS and JavaScript from the main page maybe you should consider replacing <IFRAME>
with a Ajax loaded content. This is more SEO friendly now when search bots are able to execute JavaScript.
This is jQuery example that includes another html page into your document. This is much more SEO friendly than iframe
. In order to be sure that the bots are not indexing the included page just add it to disallow in robots.txt
<html>
<header>
<script src="/js/jquery.js" type="text/javascript"></script>
</header>
<body>
<div id='include-from-outside'></div>
<script type='text/javascript'>
$('#include-from-outside').load('http://example.com/included.html');
</script>
</body>
</html>
You could also include jQuery directly from Google: http://code.google.com/apis/ajaxlibs/documentation/ — this means optional auto-inclusion of newer versions and some significant speed increase. Also, means that you have to trust them for delivering you just the jQuery
answered Mar 2, 2010 at 7:16
sorinsorin
157k172 gold badges523 silver badges784 bronze badges
0
My compact version:
<script type="text/javascript">
$(window).load(function () {
var frame = $('iframe').get(0);
if (frame != null) {
var frmHead = $(frame).contents().find('head');
if (frmHead != null) {
frmHead.append($('style, link[rel=stylesheet]').clone()); // clone existing css link
//frmHead.append($("<link/>", { rel: "stylesheet", href: "/styles/style.css", type: "text/css" })); // or create css link yourself
}
}
});
</script>
However, sometimes the iframe
is not ready on window loaded, so there is a need of using a timer.
Ready-to-use code (with timer):
<script type="text/javascript">
var frameListener;
$(window).load(function () {
frameListener = setInterval("frameLoaded()", 50);
});
function frameLoaded() {
var frame = $('iframe').get(0);
if (frame != null) {
var frmHead = $(frame).contents().find('head');
if (frmHead != null) {
clearInterval(frameListener); // stop the listener
frmHead.append($('style, link[rel=stylesheet]').clone()); // clone existing css link
//frmHead.append($("<link/>", { rel: "stylesheet", href: "/styles/style.css", type: "text/css" })); // or create css link yourself
}
}
}
</script>
…and jQuery link:
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js" type="text/javascript"></script>
Eric
6,5465 gold badges43 silver badges65 bronze badges
answered Mar 21, 2013 at 9:07
Chris WChris W
1,51219 silver badges27 bronze badges
1
As many answers are written for the same domains, I’ll write how to do this in cross domains.
First, you need to know the Post Message API. We need a messenger to communicate between two windows.
Here’s a messenger I created.
/**
* Creates a messenger between two windows
* which have two different domains
*/
class CrossMessenger {
/**
*
* @param {object} otherWindow - window object of the other
* @param {string} targetDomain - domain of the other window
* @param {object} eventHandlers - all the event names and handlers
*/
constructor(otherWindow, targetDomain, eventHandlers = {}) {
this.otherWindow = otherWindow;
this.targetDomain = targetDomain;
this.eventHandlers = eventHandlers;
window.addEventListener("message", (e) => this.receive.call(this, e));
}
post(event, data) {
try {
// data obj should have event name
var json = JSON.stringify({
event,
data
});
this.otherWindow.postMessage(json, this.targetDomain);
} catch (e) {}
}
receive(e) {
var json;
try {
json = JSON.parse(e.data ? e.data : "{}");
} catch (e) {
return;
}
var eventName = json.event,
data = json.data;
if (e.origin !== this.targetDomain)
return;
if (typeof this.eventHandlers[eventName] === "function")
this.eventHandlers[eventName](data);
}
}
Using this in two windows to communicate can solve your problem.
In the main windows,
var msger = new CrossMessenger(iframe.contentWindow, "https://iframe.s.domain");
var cssContent = Array.prototype.map.call(yourCSSElement.sheet.cssRules, css_text).join('n');
msger.post("cssContent", {
css: cssContent
})
Then, receive the event from the Iframe.
In the Iframe:
var msger = new CrossMessenger(window.parent, "https://parent.window.domain", {
cssContent: (data) => {
var cssElem = document.createElement("style");
cssElem.innerHTML = data.css;
document.head.appendChild(cssElem);
}
})
See the Complete Javascript and Iframes tutorial for more details.
answered Nov 6, 2019 at 3:53
Other answers here seem to use jQuery and CSS links.
This code uses vanilla JavaScript. It creates a new <style>
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.
var iframe = document.getElementById('the-iframe');
var style = document.createElement('style');
style.textContent =
'.some-class-name {' +
' some-style-name: some-value;' +
'}'
;
iframe.contentDocument.head.appendChild(style);
answered Jul 7, 2016 at 0:59
25406252540625
10.7k8 gold badges49 silver badges56 bronze badges
0
When you say «doc.open()» it means you can write whatever HTML tag inside the iframe, so you should write all the basic tags for the HTML page and if you want to have a CSS link in your iframe head just write an iframe with CSS link in it. I give you an example:
doc.open();
doc.write('<!DOCTYPE html><html><head><meta charset="utf-8"/><meta http-quiv="Content-Type" content="text/html; charset=utf-8"/><title>Print Frame</title><link rel="stylesheet" type="text/css" href="/css/print.css"/></head><body><table id="' + gridId + 'Printable' + '" class="print" >' + out + '</table></body></html>');
doc.close();
answered Nov 8, 2010 at 6:25
You will not be able to style the contents of the iframe this way. My suggestion would be to use serverside scripting (PHP, ASP, or a Perl script) or find an online service that will convert a feed to JavaScript code. The only other way to do it would be if you can do a serverside include.
answered Mar 31, 2009 at 21:36
1
Incase if you have access to iframe page and want a different CSS to apply on it only when you load it via iframe on your page, here I found a solution for these kind of things
this works even if iframe is loading a different domain
check about postMessage()
plan is, send the css to iframe as a message like
iframenode.postMessage('h2{color:red;}','*');
*
is to send this message irrespective of what domain it is in iframe
and receive the message in iframe and add the received message(CSS) to that document head.
code to add in iframe page
window.addEventListener('message',function(e){
if(e.data == 'send_user_details')
document.head.appendChild('<style>'+e.data+'</style>');
});
answered May 19, 2016 at 20:20
CodeRowsCodeRows
8631 gold badge8 silver badges15 bronze badges
I think the easiest way is to add another div, in the same place as the iframe, then
make its z-index
bigger than the iframe container, so you can easly just style your own div. If you need to click on it, just use pointer-events:none
on your own div, so the iframe would be working in case you need to click on it
I hope It will help someone
answered Jul 31, 2014 at 12:34
0
I found another solution to put the style in the main html like this
<style id="iframestyle">
html {
color: white;
background: black;
}
</style>
<style>
html {
color: initial;
background: initial;
}
iframe {
border: none;
}
</style>
and then in iframe do this (see the js onload)
<iframe onload="iframe.document.head.appendChild(ifstyle)" name="log" src="/upgrading.log"></iframe>
and in js
<script>
ifstyle = document.getElementById('iframestyle')
iframe = top.frames["log"];
</script>
It may not be the best solution, and it certainly can be improved, but it is another option if you want to keep a «style» tag in parent window
answered Mar 18, 2015 at 14:51
jperellijperelli
6,8985 gold badges51 silver badges83 bronze badges
Here, There are two things inside the domain
- iFrame Section
- Page Loaded inside the iFrame
So you want to style those two sections as follows,
1. Style for the iFrame Section
It can style using CSS with that respected id
or class
name. You can just style it in your parent Style sheets also.
<style>
#my_iFrame{
height: 300px;
width: 100%;
position:absolute;
top:0;
left:0;
border: 1px black solid;
}
</style>
<iframe name='iframe1' id="my_iFrame" src="#" cellspacing="0"></iframe>
2. Style the Page Loaded inside the iFrame
This Styles can be loaded from the parent page with the help of Javascript
var cssFile = document.createElement("link")
cssFile.rel = "stylesheet";
cssFile.type = "text/css";
cssFile.href = "iFramePage.css";
then set that CSS file to the respected iFrame section
//to Load in the Body Part
frames['my_iFrame'].document.body.appendChild(cssFile);
//to Load in the Head Part
frames['my_iFrame'].document.head.appendChild(cssFile);
Here, You can edit the Head Part of the Page inside the iFrame using this way also
var $iFrameHead = $("#my_iFrame").contents().find("head");
$iFrameHead.append(
$("<link/>",{
rel: "stylesheet",
href: urlPath,
type: "text/css" }
));
Jee Mok
5,8598 gold badges46 silver badges75 bronze badges
answered Dec 29, 2016 at 3:47
K.SuthagarK.Suthagar
2,1781 gold badge15 silver badges28 bronze badges
We can insert style tag into iframe.
<style type="text/css" id="cssID">
.className
{
background-color: red;
}
</style>
<iframe id="iFrameID"></iframe>
<script type="text/javascript">
$(function () {
$("#iFrameID").contents().find("head")[0].appendChild(cssID);
//Or $("#iFrameID").contents().find("head")[0].appendChild($('#cssID')[0]);
});
</script>
answered Sep 2, 2014 at 15:18
PalanikumarPalanikumar
6,8584 gold badges40 silver badges51 bronze badges
1
var link1 = document.createElement('link');
link1.type = 'text/css';
link1.rel = 'stylesheet';
link1.href = "../../assets/css/normalize.css";
window.frames['richTextField'].document.body.appendChild(link1);
answered Oct 28, 2016 at 3:14
JeevaJeeva
1,8133 gold badges14 silver badges19 bronze badges
3
This is how I’m doing in production. It’s worth bearing in mind that if the iframe belongs to other website, it will trigger the CORS error and will not work.
var $iframe = document.querySelector(`iframe`);
var doc = $iframe.contentDocument;
var style = doc.createElement("style");
style.textContent = `*{display:none!important;}`;
doc.head.append(style);
In some cases you may also want to attach a load
event to the iframe:
var $iframe = document.querySelector(`iframe`);
$iframe.addEventListener("load", function() {
var doc = $iframe.contentDocument;
var style = doc.createElement("style");
style.textContent = `*{display:none!important;}`;
doc.head.append(style);
});
answered Nov 17, 2021 at 1:47
Diego FortesDiego Fortes
8,2143 gold badges30 silver badges38 bronze badges
3
There is a wonderful script that replaces a node with an iframe version of itself.
CodePen Demo
Usage Examples:
// Single node
var component = document.querySelector('.component');
var iframe = iframify(component);
// Collection of nodes
var components = document.querySelectorAll('.component');
var iframes = Array.prototype.map.call(components, function (component) {
return iframify(component, {});
});
// With options
var component = document.querySelector('.component');
var iframe = iframify(component, {
headExtra: '<style>.component { color: red; }</style>',
metaViewport: '<meta name="viewport" content="width=device-width">'
});
answered Oct 3, 2016 at 19:41
karlisupkarlisup
66212 silver badges22 bronze badges
1
As an alternative, you can use CSS-in-JS technology, like below lib:
https://github.com/cssobj/cssobj
It can inject JS object as CSS to iframe, dynamically
answered Jan 4, 2017 at 2:27
James YangJames Yang
1,2364 gold badges14 silver badges24 bronze badges
This is just a concept, but don’t implement this without security checks and filtering! Otherwise script could hack your site!
Answer: if you control target site, you can setup the receiver script like:
1) set the iframe link with style
parameter, like:
http://your_site.com/target.php?color=red
(the last phrase is a{color:red}
encoded by urlencode
function.
2) set the receiver page target.php
like this:
<head>
..........
$col = FILTER_VAR(SANITIZE_STRING, $_GET['color']);
<style>.xyz{color: <?php echo (in_array( $col, ['red','yellow','green'])? $col : "black") ;?> } </style>
..........
answered Oct 17, 2016 at 8:01
T.ToduaT.Todua
51.3k19 gold badges224 silver badges227 bronze badges
3
Well, I have followed these steps:
- Div with a class to hold
iframe
- Add
iframe
to thediv
. - In CSS file,
divClass { width: 500px; height: 500px; }
divClass iframe { width: 100%; height: 100%; }
This works in IE 6. Should work in other browsers, do check!
Eric
6,5465 gold badges43 silver badges65 bronze badges
answered Dec 8, 2010 at 9:46
1
Asked
14 years, 3 months ago
Viewed
1.5m times
I have a simple page that has some iframe sections (to display RSS links). How can I apply the same CSS format from the main page to the page displayed in the iframe?
asked Oct 20, 2008 at 8:27
4
Edit: This does not work cross domain unless the appropriate CORS header is set.
There are two different things here: the style of the iframe block and the style of the page embedded in the iframe. You can set the style of the iframe block the usual way:
<iframe name="iframe1" id="iframe1" src="empty.htm"
frameborder="0" border="0" cellspacing="0"
style="border-style: none;width: 100%; height: 120px;"></iframe>
The style of the page embedded in the iframe must be either set by including it in the child page:
<link type="text/css" rel="Stylesheet" href="Style/simple.css" />
Or it can be loaded from the parent page with Javascript:
var cssLink = document.createElement("link");
cssLink.href = "style.css";
cssLink.rel = "stylesheet";
cssLink.type = "text/css";
frames['iframe1'].document.head.appendChild(cssLink);
brauliobo
5,5464 gold badges28 silver badges33 bronze badges
answered Oct 20, 2008 at 9:07
Tamas CzinegeTamas Czinege
117k40 gold badges148 silver badges175 bronze badges
5
I met this issue with Google Calendar. I wanted to style it on a darker background and change font.
Luckily, the URL from the embed code had no restriction on direct access, so by using PHP function file_get_contents
it is possible to get the
entire content from the page. Instead of calling the Google URL, it is possible to call a php file located on your server, ex. google.php
, which will contain the original content with modifications:
$content = file_get_contents('https://www.google.com/calendar/embed?src=%23contacts%40group.v.calendar.google.com&ctz=America/Montreal');
Adding the path to your stylesheet:
$content = str_replace('</head>','<link rel="stylesheet" href="http://www.yourwebsiteurl.com/google.css" /></head>', $content);
(This will place your stylesheet last just before the head
end tag.)
Specify the base url form the original url in case css and js are called relatively:
$content = str_replace('</title>','</title><base href="https://www.google.com/calendar/" />', $content);
The final google.php
file should look like this:
<?php
$content = file_get_contents('https://www.google.com/calendar/embed?src=%23contacts%40group.v.calendar.google.com&ctz=America/Montreal');
$content = str_replace('</title>','</title><base href="https://www.google.com/calendar/" />', $content);
$content = str_replace('</head>','<link rel="stylesheet" href="http://www.yourwebsiteurl.com/google.css" /></head>', $content);
echo $content;
Then you change the iframe
embed code to:
<iframe src="http://www.yourwebsiteurl.com/google.php" style="border: 0" width="800" height="600" frameborder="0" scrolling="no"></iframe>
Good luck!
Krish Munot
1,0632 gold badges18 silver badges28 bronze badges
answered Sep 20, 2012 at 22:21
4
If the content of the iframe is not completely under your control or you want to access the content from different pages with different styles you could try manipulating it using JavaScript.
var frm = frames['frame'].document;
var otherhead = frm.getElementsByTagName("head")[0];
var link = frm.createElement("link");
link.setAttribute("rel", "stylesheet");
link.setAttribute("type", "text/css");
link.setAttribute("href", "style.css");
otherhead.appendChild(link);
Note that depending on what browser you use this might only work on pages served from the same domain.
niccord
7444 silver badges20 bronze badges
answered Oct 20, 2008 at 8:58
Horst GutmannHorst Gutmann
10.8k2 gold badges26 silver badges31 bronze badges
5
var $head = $("#eFormIFrame").contents().find("head");
$head.append($("<link/>", {
rel: "stylesheet",
href: url,
type: "text/css"
}));
answered Nov 21, 2012 at 16:17
0
Here is how to apply CSS code directly without using <link>
to load an extra stylesheet.
var head = jQuery("#iframe").contents().find("head");
var css = '<style type="text/css">' +
'#banner{display:none}; ' +
'</style>';
jQuery(head).append(css);
This hides the banner in the iframe page. Thank you for your suggestions!
answered Oct 15, 2013 at 22:47
domihdomih
1,37016 silver badges19 bronze badges
0
If you control the page in the iframe, as hangy said, the easiest approach is to create a shared CSS file with common styles, then just link to it from your html pages.
Otherwise it is unlikely you will be able to dynamically change the style of a page from an external page in your iframe. This is because browsers have tightened the security on cross frame dom scripting due to possible misuse for spoofing and other hacks.
This tutorial may provide you with more information on scripting iframes in general. About cross frame scripting explains the security restrictions from the IE perspective.
answered Oct 20, 2008 at 8:52
AshAsh
60.3k31 gold badges151 silver badges168 bronze badges
An iframe is universally handled like a different HTML page by most browsers. If you want to apply the same stylesheet to the content of the iframe, just reference it from the pages used in there.
answered Oct 20, 2008 at 8:37
hangyhangy
10.7k6 gold badges45 silver badges63 bronze badges
1
The above with a little change works:
var cssLink = document.createElement("link")
cssLink.href = "pFstylesEditor.css";
cssLink.rel = "stylesheet";
cssLink.type = "text/css";
//Instead of this
//frames['frame1'].document.body.appendChild(cssLink);
//Do this
var doc=document.getElementById("edit").contentWindow.document;
//If you are doing any dynamic writing do that first
doc.open();
doc.write(myData);
doc.close();
//Then append child
doc.body.appendChild(cssLink);
Works fine with ff3 and ie8 at least
Eric
6,5465 gold badges43 silver badges65 bronze badges
answered Jul 28, 2009 at 22:53
0
The following worked for me.
var iframe = top.frames[name].document;
var css = '' +
'<style type="text/css">' +
'body{margin:0;padding:0;background:transparent}' +
'</style>';
iframe.open();
iframe.write(css);
iframe.close();
answered May 23, 2011 at 16:22
peterpeter
1591 silver badge2 bronze badges
0
Expanding on the above jQuery solution to cope with any delays in loading the frame contents.
$('iframe').each(function(){
function injectCSS(){
$iframe.contents().find('head').append(
$('<link/>', { rel: 'stylesheet', href: 'iframe.css', type: 'text/css' })
);
}
var $iframe = $(this);
$iframe.on('load', injectCSS);
injectCSS();
});
answered Jun 24, 2013 at 11:14
David BradshawDavid Bradshaw
11.6k3 gold badges39 silver badges67 bronze badges
0
use can try this:
$('iframe').load( function() {
$('iframe').contents().find("head")
.append($("<style type='text/css'> .my-class{display:none;} </style>"));
});
answered Sep 1, 2017 at 10:15
TherichpostTherichpost
1,7312 gold badges14 silver badges19 bronze badges
1
If you want to reuse CSS and JavaScript from the main page maybe you should consider replacing <IFRAME>
with a Ajax loaded content. This is more SEO friendly now when search bots are able to execute JavaScript.
This is jQuery example that includes another html page into your document. This is much more SEO friendly than iframe
. In order to be sure that the bots are not indexing the included page just add it to disallow in robots.txt
<html>
<header>
<script src="/js/jquery.js" type="text/javascript"></script>
</header>
<body>
<div id='include-from-outside'></div>
<script type='text/javascript'>
$('#include-from-outside').load('http://example.com/included.html');
</script>
</body>
</html>
You could also include jQuery directly from Google: http://code.google.com/apis/ajaxlibs/documentation/ — this means optional auto-inclusion of newer versions and some significant speed increase. Also, means that you have to trust them for delivering you just the jQuery
answered Mar 2, 2010 at 7:16
sorinsorin
157k172 gold badges523 silver badges784 bronze badges
0
My compact version:
<script type="text/javascript">
$(window).load(function () {
var frame = $('iframe').get(0);
if (frame != null) {
var frmHead = $(frame).contents().find('head');
if (frmHead != null) {
frmHead.append($('style, link[rel=stylesheet]').clone()); // clone existing css link
//frmHead.append($("<link/>", { rel: "stylesheet", href: "/styles/style.css", type: "text/css" })); // or create css link yourself
}
}
});
</script>
However, sometimes the iframe
is not ready on window loaded, so there is a need of using a timer.
Ready-to-use code (with timer):
<script type="text/javascript">
var frameListener;
$(window).load(function () {
frameListener = setInterval("frameLoaded()", 50);
});
function frameLoaded() {
var frame = $('iframe').get(0);
if (frame != null) {
var frmHead = $(frame).contents().find('head');
if (frmHead != null) {
clearInterval(frameListener); // stop the listener
frmHead.append($('style, link[rel=stylesheet]').clone()); // clone existing css link
//frmHead.append($("<link/>", { rel: "stylesheet", href: "/styles/style.css", type: "text/css" })); // or create css link yourself
}
}
}
</script>
…and jQuery link:
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js" type="text/javascript"></script>
Eric
6,5465 gold badges43 silver badges65 bronze badges
answered Mar 21, 2013 at 9:07
Chris WChris W
1,51219 silver badges27 bronze badges
1
As many answers are written for the same domains, I’ll write how to do this in cross domains.
First, you need to know the Post Message API. We need a messenger to communicate between two windows.
Here’s a messenger I created.
/**
* Creates a messenger between two windows
* which have two different domains
*/
class CrossMessenger {
/**
*
* @param {object} otherWindow - window object of the other
* @param {string} targetDomain - domain of the other window
* @param {object} eventHandlers - all the event names and handlers
*/
constructor(otherWindow, targetDomain, eventHandlers = {}) {
this.otherWindow = otherWindow;
this.targetDomain = targetDomain;
this.eventHandlers = eventHandlers;
window.addEventListener("message", (e) => this.receive.call(this, e));
}
post(event, data) {
try {
// data obj should have event name
var json = JSON.stringify({
event,
data
});
this.otherWindow.postMessage(json, this.targetDomain);
} catch (e) {}
}
receive(e) {
var json;
try {
json = JSON.parse(e.data ? e.data : "{}");
} catch (e) {
return;
}
var eventName = json.event,
data = json.data;
if (e.origin !== this.targetDomain)
return;
if (typeof this.eventHandlers[eventName] === "function")
this.eventHandlers[eventName](data);
}
}
Using this in two windows to communicate can solve your problem.
In the main windows,
var msger = new CrossMessenger(iframe.contentWindow, "https://iframe.s.domain");
var cssContent = Array.prototype.map.call(yourCSSElement.sheet.cssRules, css_text).join('n');
msger.post("cssContent", {
css: cssContent
})
Then, receive the event from the Iframe.
In the Iframe:
var msger = new CrossMessenger(window.parent, "https://parent.window.domain", {
cssContent: (data) => {
var cssElem = document.createElement("style");
cssElem.innerHTML = data.css;
document.head.appendChild(cssElem);
}
})
See the Complete Javascript and Iframes tutorial for more details.
answered Nov 6, 2019 at 3:53
Other answers here seem to use jQuery and CSS links.
This code uses vanilla JavaScript. It creates a new <style>
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.
var iframe = document.getElementById('the-iframe');
var style = document.createElement('style');
style.textContent =
'.some-class-name {' +
' some-style-name: some-value;' +
'}'
;
iframe.contentDocument.head.appendChild(style);
answered Jul 7, 2016 at 0:59
25406252540625
10.7k8 gold badges49 silver badges56 bronze badges
0
When you say «doc.open()» it means you can write whatever HTML tag inside the iframe, so you should write all the basic tags for the HTML page and if you want to have a CSS link in your iframe head just write an iframe with CSS link in it. I give you an example:
doc.open();
doc.write('<!DOCTYPE html><html><head><meta charset="utf-8"/><meta http-quiv="Content-Type" content="text/html; charset=utf-8"/><title>Print Frame</title><link rel="stylesheet" type="text/css" href="/css/print.css"/></head><body><table id="' + gridId + 'Printable' + '" class="print" >' + out + '</table></body></html>');
doc.close();
answered Nov 8, 2010 at 6:25
You will not be able to style the contents of the iframe this way. My suggestion would be to use serverside scripting (PHP, ASP, or a Perl script) or find an online service that will convert a feed to JavaScript code. The only other way to do it would be if you can do a serverside include.
answered Mar 31, 2009 at 21:36
1
Incase if you have access to iframe page and want a different CSS to apply on it only when you load it via iframe on your page, here I found a solution for these kind of things
this works even if iframe is loading a different domain
check about postMessage()
plan is, send the css to iframe as a message like
iframenode.postMessage('h2{color:red;}','*');
*
is to send this message irrespective of what domain it is in iframe
and receive the message in iframe and add the received message(CSS) to that document head.
code to add in iframe page
window.addEventListener('message',function(e){
if(e.data == 'send_user_details')
document.head.appendChild('<style>'+e.data+'</style>');
});
answered May 19, 2016 at 20:20
CodeRowsCodeRows
8631 gold badge8 silver badges15 bronze badges
I think the easiest way is to add another div, in the same place as the iframe, then
make its z-index
bigger than the iframe container, so you can easly just style your own div. If you need to click on it, just use pointer-events:none
on your own div, so the iframe would be working in case you need to click on it
I hope It will help someone
answered Jul 31, 2014 at 12:34
0
I found another solution to put the style in the main html like this
<style id="iframestyle">
html {
color: white;
background: black;
}
</style>
<style>
html {
color: initial;
background: initial;
}
iframe {
border: none;
}
</style>
and then in iframe do this (see the js onload)
<iframe onload="iframe.document.head.appendChild(ifstyle)" name="log" src="/upgrading.log"></iframe>
and in js
<script>
ifstyle = document.getElementById('iframestyle')
iframe = top.frames["log"];
</script>
It may not be the best solution, and it certainly can be improved, but it is another option if you want to keep a «style» tag in parent window
answered Mar 18, 2015 at 14:51
jperellijperelli
6,8985 gold badges51 silver badges83 bronze badges
Here, There are two things inside the domain
- iFrame Section
- Page Loaded inside the iFrame
So you want to style those two sections as follows,
1. Style for the iFrame Section
It can style using CSS with that respected id
or class
name. You can just style it in your parent Style sheets also.
<style>
#my_iFrame{
height: 300px;
width: 100%;
position:absolute;
top:0;
left:0;
border: 1px black solid;
}
</style>
<iframe name='iframe1' id="my_iFrame" src="#" cellspacing="0"></iframe>
2. Style the Page Loaded inside the iFrame
This Styles can be loaded from the parent page with the help of Javascript
var cssFile = document.createElement("link")
cssFile.rel = "stylesheet";
cssFile.type = "text/css";
cssFile.href = "iFramePage.css";
then set that CSS file to the respected iFrame section
//to Load in the Body Part
frames['my_iFrame'].document.body.appendChild(cssFile);
//to Load in the Head Part
frames['my_iFrame'].document.head.appendChild(cssFile);
Here, You can edit the Head Part of the Page inside the iFrame using this way also
var $iFrameHead = $("#my_iFrame").contents().find("head");
$iFrameHead.append(
$("<link/>",{
rel: "stylesheet",
href: urlPath,
type: "text/css" }
));
Jee Mok
5,8598 gold badges46 silver badges75 bronze badges
answered Dec 29, 2016 at 3:47
K.SuthagarK.Suthagar
2,1781 gold badge15 silver badges28 bronze badges
We can insert style tag into iframe.
<style type="text/css" id="cssID">
.className
{
background-color: red;
}
</style>
<iframe id="iFrameID"></iframe>
<script type="text/javascript">
$(function () {
$("#iFrameID").contents().find("head")[0].appendChild(cssID);
//Or $("#iFrameID").contents().find("head")[0].appendChild($('#cssID')[0]);
});
</script>
answered Sep 2, 2014 at 15:18
PalanikumarPalanikumar
6,8584 gold badges40 silver badges51 bronze badges
1
var link1 = document.createElement('link');
link1.type = 'text/css';
link1.rel = 'stylesheet';
link1.href = "../../assets/css/normalize.css";
window.frames['richTextField'].document.body.appendChild(link1);
answered Oct 28, 2016 at 3:14
JeevaJeeva
1,8133 gold badges14 silver badges19 bronze badges
3
This is how I’m doing in production. It’s worth bearing in mind that if the iframe belongs to other website, it will trigger the CORS error and will not work.
var $iframe = document.querySelector(`iframe`);
var doc = $iframe.contentDocument;
var style = doc.createElement("style");
style.textContent = `*{display:none!important;}`;
doc.head.append(style);
In some cases you may also want to attach a load
event to the iframe:
var $iframe = document.querySelector(`iframe`);
$iframe.addEventListener("load", function() {
var doc = $iframe.contentDocument;
var style = doc.createElement("style");
style.textContent = `*{display:none!important;}`;
doc.head.append(style);
});
answered Nov 17, 2021 at 1:47
Diego FortesDiego Fortes
8,2143 gold badges30 silver badges38 bronze badges
3
There is a wonderful script that replaces a node with an iframe version of itself.
CodePen Demo
Usage Examples:
// Single node
var component = document.querySelector('.component');
var iframe = iframify(component);
// Collection of nodes
var components = document.querySelectorAll('.component');
var iframes = Array.prototype.map.call(components, function (component) {
return iframify(component, {});
});
// With options
var component = document.querySelector('.component');
var iframe = iframify(component, {
headExtra: '<style>.component { color: red; }</style>',
metaViewport: '<meta name="viewport" content="width=device-width">'
});
answered Oct 3, 2016 at 19:41
karlisupkarlisup
66212 silver badges22 bronze badges
1
As an alternative, you can use CSS-in-JS technology, like below lib:
https://github.com/cssobj/cssobj
It can inject JS object as CSS to iframe, dynamically
answered Jan 4, 2017 at 2:27
James YangJames Yang
1,2364 gold badges14 silver badges24 bronze badges
This is just a concept, but don’t implement this without security checks and filtering! Otherwise script could hack your site!
Answer: if you control target site, you can setup the receiver script like:
1) set the iframe link with style
parameter, like:
http://your_site.com/target.php?color=red
(the last phrase is a{color:red}
encoded by urlencode
function.
2) set the receiver page target.php
like this:
<head>
..........
$col = FILTER_VAR(SANITIZE_STRING, $_GET['color']);
<style>.xyz{color: <?php echo (in_array( $col, ['red','yellow','green'])? $col : "black") ;?> } </style>
..........
answered Oct 17, 2016 at 8:01
T.ToduaT.Todua
51.3k19 gold badges224 silver badges227 bronze badges
3
Well, I have followed these steps:
- Div with a class to hold
iframe
- Add
iframe
to thediv
. - In CSS file,
divClass { width: 500px; height: 500px; }
divClass iframe { width: 100%; height: 100%; }
This works in IE 6. Should work in other browsers, do check!
Eric
6,5465 gold badges43 silver badges65 bronze badges
answered Dec 8, 2010 at 9:46
1
Asked
14 years, 3 months ago
Viewed
1.5m times
I have a simple page that has some iframe sections (to display RSS links). How can I apply the same CSS format from the main page to the page displayed in the iframe?
asked Oct 20, 2008 at 8:27
4
Edit: This does not work cross domain unless the appropriate CORS header is set.
There are two different things here: the style of the iframe block and the style of the page embedded in the iframe. You can set the style of the iframe block the usual way:
<iframe name="iframe1" id="iframe1" src="empty.htm"
frameborder="0" border="0" cellspacing="0"
style="border-style: none;width: 100%; height: 120px;"></iframe>
The style of the page embedded in the iframe must be either set by including it in the child page:
<link type="text/css" rel="Stylesheet" href="Style/simple.css" />
Or it can be loaded from the parent page with Javascript:
var cssLink = document.createElement("link");
cssLink.href = "style.css";
cssLink.rel = "stylesheet";
cssLink.type = "text/css";
frames['iframe1'].document.head.appendChild(cssLink);
brauliobo
5,5464 gold badges28 silver badges33 bronze badges
answered Oct 20, 2008 at 9:07
Tamas CzinegeTamas Czinege
117k40 gold badges148 silver badges175 bronze badges
5
I met this issue with Google Calendar. I wanted to style it on a darker background and change font.
Luckily, the URL from the embed code had no restriction on direct access, so by using PHP function file_get_contents
it is possible to get the
entire content from the page. Instead of calling the Google URL, it is possible to call a php file located on your server, ex. google.php
, which will contain the original content with modifications:
$content = file_get_contents('https://www.google.com/calendar/embed?src=%23contacts%40group.v.calendar.google.com&ctz=America/Montreal');
Adding the path to your stylesheet:
$content = str_replace('</head>','<link rel="stylesheet" href="http://www.yourwebsiteurl.com/google.css" /></head>', $content);
(This will place your stylesheet last just before the head
end tag.)
Specify the base url form the original url in case css and js are called relatively:
$content = str_replace('</title>','</title><base href="https://www.google.com/calendar/" />', $content);
The final google.php
file should look like this:
<?php
$content = file_get_contents('https://www.google.com/calendar/embed?src=%23contacts%40group.v.calendar.google.com&ctz=America/Montreal');
$content = str_replace('</title>','</title><base href="https://www.google.com/calendar/" />', $content);
$content = str_replace('</head>','<link rel="stylesheet" href="http://www.yourwebsiteurl.com/google.css" /></head>', $content);
echo $content;
Then you change the iframe
embed code to:
<iframe src="http://www.yourwebsiteurl.com/google.php" style="border: 0" width="800" height="600" frameborder="0" scrolling="no"></iframe>
Good luck!
Krish Munot
1,0632 gold badges18 silver badges28 bronze badges
answered Sep 20, 2012 at 22:21
4
If the content of the iframe is not completely under your control or you want to access the content from different pages with different styles you could try manipulating it using JavaScript.
var frm = frames['frame'].document;
var otherhead = frm.getElementsByTagName("head")[0];
var link = frm.createElement("link");
link.setAttribute("rel", "stylesheet");
link.setAttribute("type", "text/css");
link.setAttribute("href", "style.css");
otherhead.appendChild(link);
Note that depending on what browser you use this might only work on pages served from the same domain.
niccord
7444 silver badges20 bronze badges
answered Oct 20, 2008 at 8:58
Horst GutmannHorst Gutmann
10.8k2 gold badges26 silver badges31 bronze badges
5
var $head = $("#eFormIFrame").contents().find("head");
$head.append($("<link/>", {
rel: "stylesheet",
href: url,
type: "text/css"
}));
answered Nov 21, 2012 at 16:17
0
Here is how to apply CSS code directly without using <link>
to load an extra stylesheet.
var head = jQuery("#iframe").contents().find("head");
var css = '<style type="text/css">' +
'#banner{display:none}; ' +
'</style>';
jQuery(head).append(css);
This hides the banner in the iframe page. Thank you for your suggestions!
answered Oct 15, 2013 at 22:47
domihdomih
1,37016 silver badges19 bronze badges
0
If you control the page in the iframe, as hangy said, the easiest approach is to create a shared CSS file with common styles, then just link to it from your html pages.
Otherwise it is unlikely you will be able to dynamically change the style of a page from an external page in your iframe. This is because browsers have tightened the security on cross frame dom scripting due to possible misuse for spoofing and other hacks.
This tutorial may provide you with more information on scripting iframes in general. About cross frame scripting explains the security restrictions from the IE perspective.
answered Oct 20, 2008 at 8:52
AshAsh
60.3k31 gold badges151 silver badges168 bronze badges
An iframe is universally handled like a different HTML page by most browsers. If you want to apply the same stylesheet to the content of the iframe, just reference it from the pages used in there.
answered Oct 20, 2008 at 8:37
hangyhangy
10.7k6 gold badges45 silver badges63 bronze badges
1
The above with a little change works:
var cssLink = document.createElement("link")
cssLink.href = "pFstylesEditor.css";
cssLink.rel = "stylesheet";
cssLink.type = "text/css";
//Instead of this
//frames['frame1'].document.body.appendChild(cssLink);
//Do this
var doc=document.getElementById("edit").contentWindow.document;
//If you are doing any dynamic writing do that first
doc.open();
doc.write(myData);
doc.close();
//Then append child
doc.body.appendChild(cssLink);
Works fine with ff3 and ie8 at least
Eric
6,5465 gold badges43 silver badges65 bronze badges
answered Jul 28, 2009 at 22:53
0
The following worked for me.
var iframe = top.frames[name].document;
var css = '' +
'<style type="text/css">' +
'body{margin:0;padding:0;background:transparent}' +
'</style>';
iframe.open();
iframe.write(css);
iframe.close();
answered May 23, 2011 at 16:22
peterpeter
1591 silver badge2 bronze badges
0
Expanding on the above jQuery solution to cope with any delays in loading the frame contents.
$('iframe').each(function(){
function injectCSS(){
$iframe.contents().find('head').append(
$('<link/>', { rel: 'stylesheet', href: 'iframe.css', type: 'text/css' })
);
}
var $iframe = $(this);
$iframe.on('load', injectCSS);
injectCSS();
});
answered Jun 24, 2013 at 11:14
David BradshawDavid Bradshaw
11.6k3 gold badges39 silver badges67 bronze badges
0
use can try this:
$('iframe').load( function() {
$('iframe').contents().find("head")
.append($("<style type='text/css'> .my-class{display:none;} </style>"));
});
answered Sep 1, 2017 at 10:15
TherichpostTherichpost
1,7312 gold badges14 silver badges19 bronze badges
1
If you want to reuse CSS and JavaScript from the main page maybe you should consider replacing <IFRAME>
with a Ajax loaded content. This is more SEO friendly now when search bots are able to execute JavaScript.
This is jQuery example that includes another html page into your document. This is much more SEO friendly than iframe
. In order to be sure that the bots are not indexing the included page just add it to disallow in robots.txt
<html>
<header>
<script src="/js/jquery.js" type="text/javascript"></script>
</header>
<body>
<div id='include-from-outside'></div>
<script type='text/javascript'>
$('#include-from-outside').load('http://example.com/included.html');
</script>
</body>
</html>
You could also include jQuery directly from Google: http://code.google.com/apis/ajaxlibs/documentation/ — this means optional auto-inclusion of newer versions and some significant speed increase. Also, means that you have to trust them for delivering you just the jQuery
answered Mar 2, 2010 at 7:16
sorinsorin
157k172 gold badges523 silver badges784 bronze badges
0
My compact version:
<script type="text/javascript">
$(window).load(function () {
var frame = $('iframe').get(0);
if (frame != null) {
var frmHead = $(frame).contents().find('head');
if (frmHead != null) {
frmHead.append($('style, link[rel=stylesheet]').clone()); // clone existing css link
//frmHead.append($("<link/>", { rel: "stylesheet", href: "/styles/style.css", type: "text/css" })); // or create css link yourself
}
}
});
</script>
However, sometimes the iframe
is not ready on window loaded, so there is a need of using a timer.
Ready-to-use code (with timer):
<script type="text/javascript">
var frameListener;
$(window).load(function () {
frameListener = setInterval("frameLoaded()", 50);
});
function frameLoaded() {
var frame = $('iframe').get(0);
if (frame != null) {
var frmHead = $(frame).contents().find('head');
if (frmHead != null) {
clearInterval(frameListener); // stop the listener
frmHead.append($('style, link[rel=stylesheet]').clone()); // clone existing css link
//frmHead.append($("<link/>", { rel: "stylesheet", href: "/styles/style.css", type: "text/css" })); // or create css link yourself
}
}
}
</script>
…and jQuery link:
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js" type="text/javascript"></script>
Eric
6,5465 gold badges43 silver badges65 bronze badges
answered Mar 21, 2013 at 9:07
Chris WChris W
1,51219 silver badges27 bronze badges
1
As many answers are written for the same domains, I’ll write how to do this in cross domains.
First, you need to know the Post Message API. We need a messenger to communicate between two windows.
Here’s a messenger I created.
/**
* Creates a messenger between two windows
* which have two different domains
*/
class CrossMessenger {
/**
*
* @param {object} otherWindow - window object of the other
* @param {string} targetDomain - domain of the other window
* @param {object} eventHandlers - all the event names and handlers
*/
constructor(otherWindow, targetDomain, eventHandlers = {}) {
this.otherWindow = otherWindow;
this.targetDomain = targetDomain;
this.eventHandlers = eventHandlers;
window.addEventListener("message", (e) => this.receive.call(this, e));
}
post(event, data) {
try {
// data obj should have event name
var json = JSON.stringify({
event,
data
});
this.otherWindow.postMessage(json, this.targetDomain);
} catch (e) {}
}
receive(e) {
var json;
try {
json = JSON.parse(e.data ? e.data : "{}");
} catch (e) {
return;
}
var eventName = json.event,
data = json.data;
if (e.origin !== this.targetDomain)
return;
if (typeof this.eventHandlers[eventName] === "function")
this.eventHandlers[eventName](data);
}
}
Using this in two windows to communicate can solve your problem.
In the main windows,
var msger = new CrossMessenger(iframe.contentWindow, "https://iframe.s.domain");
var cssContent = Array.prototype.map.call(yourCSSElement.sheet.cssRules, css_text).join('n');
msger.post("cssContent", {
css: cssContent
})
Then, receive the event from the Iframe.
In the Iframe:
var msger = new CrossMessenger(window.parent, "https://parent.window.domain", {
cssContent: (data) => {
var cssElem = document.createElement("style");
cssElem.innerHTML = data.css;
document.head.appendChild(cssElem);
}
})
See the Complete Javascript and Iframes tutorial for more details.
answered Nov 6, 2019 at 3:53
Other answers here seem to use jQuery and CSS links.
This code uses vanilla JavaScript. It creates a new <style>
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.
var iframe = document.getElementById('the-iframe');
var style = document.createElement('style');
style.textContent =
'.some-class-name {' +
' some-style-name: some-value;' +
'}'
;
iframe.contentDocument.head.appendChild(style);
answered Jul 7, 2016 at 0:59
25406252540625
10.7k8 gold badges49 silver badges56 bronze badges
0
When you say «doc.open()» it means you can write whatever HTML tag inside the iframe, so you should write all the basic tags for the HTML page and if you want to have a CSS link in your iframe head just write an iframe with CSS link in it. I give you an example:
doc.open();
doc.write('<!DOCTYPE html><html><head><meta charset="utf-8"/><meta http-quiv="Content-Type" content="text/html; charset=utf-8"/><title>Print Frame</title><link rel="stylesheet" type="text/css" href="/css/print.css"/></head><body><table id="' + gridId + 'Printable' + '" class="print" >' + out + '</table></body></html>');
doc.close();
answered Nov 8, 2010 at 6:25
You will not be able to style the contents of the iframe this way. My suggestion would be to use serverside scripting (PHP, ASP, or a Perl script) or find an online service that will convert a feed to JavaScript code. The only other way to do it would be if you can do a serverside include.
answered Mar 31, 2009 at 21:36
1
Incase if you have access to iframe page and want a different CSS to apply on it only when you load it via iframe on your page, here I found a solution for these kind of things
this works even if iframe is loading a different domain
check about postMessage()
plan is, send the css to iframe as a message like
iframenode.postMessage('h2{color:red;}','*');
*
is to send this message irrespective of what domain it is in iframe
and receive the message in iframe and add the received message(CSS) to that document head.
code to add in iframe page
window.addEventListener('message',function(e){
if(e.data == 'send_user_details')
document.head.appendChild('<style>'+e.data+'</style>');
});
answered May 19, 2016 at 20:20
CodeRowsCodeRows
8631 gold badge8 silver badges15 bronze badges
I think the easiest way is to add another div, in the same place as the iframe, then
make its z-index
bigger than the iframe container, so you can easly just style your own div. If you need to click on it, just use pointer-events:none
on your own div, so the iframe would be working in case you need to click on it
I hope It will help someone
answered Jul 31, 2014 at 12:34
0
I found another solution to put the style in the main html like this
<style id="iframestyle">
html {
color: white;
background: black;
}
</style>
<style>
html {
color: initial;
background: initial;
}
iframe {
border: none;
}
</style>
and then in iframe do this (see the js onload)
<iframe onload="iframe.document.head.appendChild(ifstyle)" name="log" src="/upgrading.log"></iframe>
and in js
<script>
ifstyle = document.getElementById('iframestyle')
iframe = top.frames["log"];
</script>
It may not be the best solution, and it certainly can be improved, but it is another option if you want to keep a «style» tag in parent window
answered Mar 18, 2015 at 14:51
jperellijperelli
6,8985 gold badges51 silver badges83 bronze badges
Here, There are two things inside the domain
- iFrame Section
- Page Loaded inside the iFrame
So you want to style those two sections as follows,
1. Style for the iFrame Section
It can style using CSS with that respected id
or class
name. You can just style it in your parent Style sheets also.
<style>
#my_iFrame{
height: 300px;
width: 100%;
position:absolute;
top:0;
left:0;
border: 1px black solid;
}
</style>
<iframe name='iframe1' id="my_iFrame" src="#" cellspacing="0"></iframe>
2. Style the Page Loaded inside the iFrame
This Styles can be loaded from the parent page with the help of Javascript
var cssFile = document.createElement("link")
cssFile.rel = "stylesheet";
cssFile.type = "text/css";
cssFile.href = "iFramePage.css";
then set that CSS file to the respected iFrame section
//to Load in the Body Part
frames['my_iFrame'].document.body.appendChild(cssFile);
//to Load in the Head Part
frames['my_iFrame'].document.head.appendChild(cssFile);
Here, You can edit the Head Part of the Page inside the iFrame using this way also
var $iFrameHead = $("#my_iFrame").contents().find("head");
$iFrameHead.append(
$("<link/>",{
rel: "stylesheet",
href: urlPath,
type: "text/css" }
));
Jee Mok
5,8598 gold badges46 silver badges75 bronze badges
answered Dec 29, 2016 at 3:47
K.SuthagarK.Suthagar
2,1781 gold badge15 silver badges28 bronze badges
We can insert style tag into iframe.
<style type="text/css" id="cssID">
.className
{
background-color: red;
}
</style>
<iframe id="iFrameID"></iframe>
<script type="text/javascript">
$(function () {
$("#iFrameID").contents().find("head")[0].appendChild(cssID);
//Or $("#iFrameID").contents().find("head")[0].appendChild($('#cssID')[0]);
});
</script>
answered Sep 2, 2014 at 15:18
PalanikumarPalanikumar
6,8584 gold badges40 silver badges51 bronze badges
1
var link1 = document.createElement('link');
link1.type = 'text/css';
link1.rel = 'stylesheet';
link1.href = "../../assets/css/normalize.css";
window.frames['richTextField'].document.body.appendChild(link1);
answered Oct 28, 2016 at 3:14
JeevaJeeva
1,8133 gold badges14 silver badges19 bronze badges
3
This is how I’m doing in production. It’s worth bearing in mind that if the iframe belongs to other website, it will trigger the CORS error and will not work.
var $iframe = document.querySelector(`iframe`);
var doc = $iframe.contentDocument;
var style = doc.createElement("style");
style.textContent = `*{display:none!important;}`;
doc.head.append(style);
In some cases you may also want to attach a load
event to the iframe:
var $iframe = document.querySelector(`iframe`);
$iframe.addEventListener("load", function() {
var doc = $iframe.contentDocument;
var style = doc.createElement("style");
style.textContent = `*{display:none!important;}`;
doc.head.append(style);
});
answered Nov 17, 2021 at 1:47
Diego FortesDiego Fortes
8,2143 gold badges30 silver badges38 bronze badges
3
There is a wonderful script that replaces a node with an iframe version of itself.
CodePen Demo
Usage Examples:
// Single node
var component = document.querySelector('.component');
var iframe = iframify(component);
// Collection of nodes
var components = document.querySelectorAll('.component');
var iframes = Array.prototype.map.call(components, function (component) {
return iframify(component, {});
});
// With options
var component = document.querySelector('.component');
var iframe = iframify(component, {
headExtra: '<style>.component { color: red; }</style>',
metaViewport: '<meta name="viewport" content="width=device-width">'
});
answered Oct 3, 2016 at 19:41
karlisupkarlisup
66212 silver badges22 bronze badges
1
As an alternative, you can use CSS-in-JS technology, like below lib:
https://github.com/cssobj/cssobj
It can inject JS object as CSS to iframe, dynamically
answered Jan 4, 2017 at 2:27
James YangJames Yang
1,2364 gold badges14 silver badges24 bronze badges
This is just a concept, but don’t implement this without security checks and filtering! Otherwise script could hack your site!
Answer: if you control target site, you can setup the receiver script like:
1) set the iframe link with style
parameter, like:
http://your_site.com/target.php?color=red
(the last phrase is a{color:red}
encoded by urlencode
function.
2) set the receiver page target.php
like this:
<head>
..........
$col = FILTER_VAR(SANITIZE_STRING, $_GET['color']);
<style>.xyz{color: <?php echo (in_array( $col, ['red','yellow','green'])? $col : "black") ;?> } </style>
..........
answered Oct 17, 2016 at 8:01
T.ToduaT.Todua
51.3k19 gold badges224 silver badges227 bronze badges
3
Well, I have followed these steps:
- Div with a class to hold
iframe
- Add
iframe
to thediv
. - In CSS file,
divClass { width: 500px; height: 500px; }
divClass iframe { width: 100%; height: 100%; }
This works in IE 6. Should work in other browsers, do check!
Eric
6,5465 gold badges43 silver badges65 bronze badges
answered Dec 8, 2010 at 9:46
1
What is an Iframe?
- An IFrame (Inline Frame) is an HTML document embedded inside another HTML document on a website.
- The IFrame HTML element is often used to insert content from another source, such as an advertisement, into a Web page.
- Although an IFrame behaves like an inline image, it can be configured with its own scrollbar independent of the surrounding page’s scrollbar.
- A Web designer can change an IFrame’s content without requiring the user to reload the surrounding page.
- This capacity is enabled through JavaScript or the target attribute of an HTML anchor.
- Web designers use IFrames to embed interactive applications in Web pages, including those that employ Ajax (Asynchronous JavaScript and XML), like Google Maps or ecommerce applications.
- An iframe is universally handled like a different HTML page by most browsers.
- If you want to apply the same stylesheet to the content of the iframe, just reference it from the pages used in there.
Applying CSS to iframe
How to apply :
- If you want to apply the same stylesheet to the content of the iframe, just reference it from the pages used in there.
- If you control the page in the iframe, the easiest approach is to create a shared CSS file with common styles, then just link to it from your html pages.
- When you embed an IFRAME element in your HTML, you have two opportunities to add CSS styles to it:
- You can style the IFRAME itself.
- You can style the page inside the IFRAME (under certain conditions).
Using CSS to style the IFRAME element:
- The first thing you should consider when styling your iframes is the IFRAME itself.
- While most browsers include iframes without a lot of extra styles, it’s still a good idea to add some styles to keep them consistent.
Here are some CSS styles :
-
- margin: 0;
- padding: 0;
- border: none;
- width: value;
- height: value;
- Here are examples of a frame with no styles and one with just the basics styled.
- These styles mostly just remove the border around the iframe, but they also ensure that all browsers display that iframe with the same margins, padding, and dimensions.
- HTML5 recommends that you use the overflow property to remove the scroll bars, but that isn’t reliable.
- So if you want to remove or change the scroll bars, you should use the scrolling attribute on your iframe as well.
- To use the scrolling attribute, add it like any other attribute and then choose one of three values: yes, no, or auto.
- Yes tells the browser to always include scroll bars even if they aren’t needed.
- No says to remove all scroll bars whether needed or not.
- Auto is the default and includes the scroll bars when they are needed and removes them when they are not.
[pastacode lang=”markup” manual=”%3Ciframe%20src%3D%22iframe.html%22%20scrolling%3D%22no%22%3E%0AThis%20is%20an%20iframe.%0A%3C%2Fiframe%3E%0A” message=”html code” highlight=”” provider=”manual”/]
- To turn off scrolling in HTML5 you are supposed to use the overflow property.
- But in these examples it doesn’t work reliably in all browsers yet. Here’s how you would turn on scrolling all the time with the overflow property:
[pastacode lang=”markup” manual=”%3Ciframe%20src%3D%22iframe.html%22%20style%3D%22overflow%3A%20scroll%3B%22%3E%0AThis%20is%20an%20iframe.%0A%3C%2Fiframe%3E%0A” message=”html code” highlight=”” provider=”manual”/]
Using The IFRAME element
-
How to use the IFRAME element :
- src—the URL for the source of the frame
- height—the height of the window
- width—the width of the window
- name—the name of the window
- srcdoc—the HTML for the source of the frame. This attribute takes precedence over any URL in the src attribute
- sandbox—a list of features that should be allowed or disallowed in the frame window
- seamless—tells the user agent that the iframe should be rendered like it is invisibly part of the parent document
- Long desc — instead, use an A element to link to a description
- Align — instead, use the CSS float property
- Allow transparency — instead, use the CSS background property to make the iframe transparent
- Frame border — instead use the border CSS property
- Margin height — instead, use the CSS margin property
- Margin width — instead, use the CSS margin property
- Scrolling — instead, use the CSS overflow property
IFRAME browser support :
- The IFRAME element is supported by all modern browsers:
- Android
- Chrome
- Firefox
- Internet Explorer 2+
- iOS / Safari Mobile
- Netscape 7+
- Opera 3+
- Safari
- Using overflow to turn off scrolling is not reliable. If you don’t want scrollbars on your iframes, you should continue to use the scrolling attribute.
- The srcdoc, sandbox, and seamless attributes are not supported by any browsers at this time.
Sample Program :
[pastacode lang=”css” manual=”%3Cstyle%20type%3D%22text%2Fcss%22%20id%3D%22cssID%22%3E%0A.className%0A%7B%0A%20%20%20%20background-color%3A%20red%3B%0A%7D%0A%3C%2Fstyle%3E%0A%0A%3Ciframe%20id%3D%22iFrameID%22%3E%3C%2Fiframe%3E%0A%0A%3Cscript%20type%3D%22text%2Fjavascript%22%3E%0A%20%20%20%20%24(function%20()%20%7B%0A%20%20%20%20%20%20%20%20%24(%22%23iFrameID%22).contents().find(%22head%22)%5B0%5D.appendChild(cssID)%3B%0A%20%20%20%20%20%20%20%20%2F%2FOr%20%24(%22%23iFrameID%22).contents().find(%22head%22)%5B0%5D.appendChild(%24(‘%23cssID’)%5B0%5D)%3B%0A%20%20%20%20%7D)%3B%0A%3C%2Fscript%3E%0A” message=”css code” highlight=”” provider=”manual”/]
Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I’m a frequent speaker at tech conferences and events.
Related Tags
- add css to iframe,
- apply css to iframe content,
- apply css to iframe content cross domain,
- apply css to iframe from parent,
- change css inside iframe jquery,
- css not working inside iframe,
- CSS override body style for content in iframe?,
- Edit IFrames CSS From External Page,
- How to apply css to iframe content?,
- How to Inject Custom HTML and CSS into an iframe,
- html — How to apply CSS to iframe?,
- html — How to applying css style into an iframe content?,
- iframe css example,
- iframe css scrolling,
- inject css into iframe,
- jquery — Add CSS to iFrame,
- jquery — How to add CSS to iframe content,
- override css inside iframe,
- override iframe css jquery,
- Overriding CSS inside an iframe
На чтение 3 мин. Просмотров 1.4k. Опубликовано 06.07.2019
Содержание
- Понимание того, как IFrames работают в веб-дизайне
- Использование CSS для стилизации элемента IFRAME
- Стилизация содержимого Iframe
Понимание того, как IFrames работают в веб-дизайне
Когда вы встраиваете элемент в ваш HTML, у вас есть две возможности добавить к нему стили CSS:
-
Вы можете стилизовать сам
IFRAME
.
-
Вы можете оформить страницу внутри
IFRAME
(при определенных условиях).
Использование CSS для стилизации элемента IFRAME
Первое, что вы должны учитывать при оформлении ваших фреймов, это
IFRAME
-
сам. Хотя большинство браузеров включают в себя iframes без большого количества дополнительных стилей, все же будет хорошей идеей добавить некоторые стили, чтобы сохранить их согласованность. Вот некоторые стили CSS, которые я всегда включаю в свои iframes:
margin: 0;
-
отступ: 0;
-
border: none;
-
width: value ;
-
height: value ;
С
ширина
а также
высота
установите размер, который подходит для моего документа. Вот примеры фрейма без стилей и стиля с базовыми стилями. Как видите, эти стили в основном просто удаляют границу вокруг iframe, но они также гарантируют, что все браузеры отображают этот iframe с одинаковыми полями, отступами и размерами. HTML5 рекомендует использовать
переполнение
свойство удалять полосы прокрутки, но это не надежно. Так что если вы хотите удалить или изменить полосы прокрутки, вы должны использовать
прокрутка
атрибут на вашем iframe, а также. Чтобы использовать
прокрутка
атрибут, добавьте его как любой другой атрибут и затем выберите одно из трех значений:
да
,
нет
, или же
auto
,
да
говорит браузеру всегда включать полосы прокрутки, даже если они не нужны.
нет
говорит удалить все полосы прокрутки, нужно ли это или нет.
auto
по умолчанию и включает полосы прокрутки, когда они необходимы, и удаляет их, когда они не нужны. Вот как отключить прокрутку с помощью
Атрибут
scrolling
: scrolling = "no" >
Это iframe.
Чтобы отключить прокрутку в HTML5, вы должны использовать
переполнение
имущество. Но, как вы можете видеть в этих примерах, он еще не работает надежно во всех браузерах. Вот как вы можете включить прокрутку все время с помощью
overflow
property: style = "overflow: scroll;" >
Это iframe.
невозможно полностью отключить прокрутку с помощью
переполнение
имущество. Многие дизайнеры хотят, чтобы их фреймы гармонировали с фоном страницы, на которой они находятся, чтобы читатели не знали, что фреймы даже есть. Но вы также можете добавить стили, чтобы выделить их. Настроить границы так, чтобы iframe показывался более легко, легко. Просто используйте
border
свойство стиля (или оно связано
border-top
,
border-right
,
border-left
, а также
свойства border-bottom
) для оформления границ: iframe {
border-top: # c00 1px dotted;
border-right: # c00 2px dotted;
border -left: # c00 2px с точками;
border-bottom: # c00 4px с точками;
}
Но вы не должны останавливаться на прокрутке и границах для ваших стилей. Вы можете применить множество других стилей CSS к вашему iframe. В этом примере используются стили CSS3 для придания iframe тени, закругленных углов и поворота на 20 градусов.
iframe {
margin-top: 20px;
margin-bottom: 30px;
-moz-border-radius: 12px;
-webkit-border-radius: 12px ;
border-radius: 12px;
-moz-box-shadow: 4px 4px 14px # 000;
-webkit-box-shadow: 4px 4px 14px # 000;
box -shadow: 4px 4px 14px # 000;
-moz-transform: повернуть (20 градусов);
-webkit-transform: повернуть (20 градусов);
-o-преобразовать: повернуть (20deg) ;
-ms-transform: поворот (20 градусов);
фильтр: progid: DXImageTransform.Microsoft.BasicImage (вращение = .2);
}
Стилизация содержимого Iframe
Стилизация содержимого 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 + '<style>/******* Put your styles here *******</style>'; }
Or you can do it with jQuery.
$("#myiFrame").on("load", function() { let head = $("#myiFrame").contents().find("head"); let css = '<style>/********* Put your styles here **********</style>'; $(head).append(css); });
Example
For example, here is the 3D CSS Progressbar tutorial page that we want to add to ours using iframe.
<iframe id="myiFrame" width="1024px" height="768px" src="http://127.0.0.1:5501/bar"></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.
.bar { width: 45%; /* This will not work */ }
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 + '<style>.bar {width:45%;}</style>'; }
Here is the result.
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.
window.onload = function() { let link = document.createElement("link"); link.href = "style.css"; /**** your CSS file ****/ link.rel = "stylesheet"; link.type = "text/css"; frames[0].document.head.appendChild(link); /**** 0 is an index of your iframe ****/ }
Note
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.
Written By