CSS conflict when using iFrame [duplicate] - html

Is it possible to change styles of a div that resides inside an iframe on the page using CSS only?

You need JavaScript. It is the same as doing it in the parent page, except you must prefix your JavaScript command with the name of the iframe.
Remember, the same origin policy applies, so you can only do this to an iframe element which is coming from your own server.
I use the Prototype framework to make it easier:
frame1.$('mydiv').style.border = '1px solid #000000'
or
frame1.$('mydiv').addClassName('withborder')

In short no.
You can not apply CSS to HTML that is loaded in an iframe, unless you have control over the page loaded in the iframe due to cross-domain resource restrictions.

Yes. Take a look at this other thread for details:
How to apply CSS to iframe?
const cssLink = document.createElement("link");
cssLink.href = "style.css";
cssLink.rel = "stylesheet";
cssLink.type = "text/css";
frames['frame1'].contentWindow.document.body.appendChild(cssLink);
// ^frame1 is the #id of the iframe: <iframe id="frame1">

You can retrieve the contents of an iframe first and then use jQuery selectors against them as usual.
$("#iframe-id").contents().find("img").attr("style","width:100%;height:100%")
$("#iframe-id").contents().find("img").addClass("fancy-zoom")
$("#iframe-id").contents().find("img").onclick(function(){ zoomit($(this)); });
Good Luck!

The quick answer is: No, sorry.
It's not possible using just CSS. You basically need to have control over the iframe content in order to style it. There are methods using javascript or your web language of choice (which I've read a little about, but am not to familiar with myself) to insert some needed styles dynamically, but you would need direct control over the iframe content, which it sounds like you do not have.

Use Jquery and wait till the source is loaded,
This is how I have achieved(Used angular interval, you can use javascript setInterval method):
var addCssToIframe = function() {
if ($('#myIframe').contents().find("head") != undefined) {
$('#myIframe')
.contents()
.find("head")
.append(
'<link rel="stylesheet" href="app/css/iframe.css" type="text/css" />');
$interval.cancel(addCssInterval);
}
};
var addCssInterval = $interval(addCssToIframe, 500, 0, false);

Combining the different solutions, this is what worked for me.
$(document).ready(function () {
$('iframe').on('load', function() {
$("iframe").contents().find("#back-link").css("display", "none");
});
});

Apparently it can be done via jQuery:
$('iframe').load( function() {
$('iframe').contents().find("head")
.append($("<style type='text/css'> .my-class{display:none;} </style>"));
});
https://stackoverflow.com/a/13959836/1625795

probably not the way you are thinking. the iframe would have to <link> in the css file too. AND you can't do it even with javascript if it's on a different domain.

Not possible from client side . A javascript error will be raised "Error: Permission denied to access property "document"" since the Iframe is not part of your domaine.
The only solution is to fetch the page from the server side code and change the needed CSS.

A sort of hack-ish way of doing things is like Eugene said. I ended up following his code and linking to my custom Css for the page. The problem for me was that, With a twitter timeline you have to do some sidestepping of twitter to override their code a smidgen. Now we have a rolling timeline with our css to it, I.E. Larger font, proper line height and making the scrollbar hidden for heights larger than their limits.
var c = document.createElement('link');
setTimeout(frames[0].document.body.appendChild(c),500); // Mileage varies by connection. Bump 500 a bit higher if necessary

Just add this and all works well:
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">

If the iframe comes from another server, you will have CORS ERRORS like:
Uncaught DOMException: Blocked a frame with origin "https://your-site.com" from accessing a cross-origin frame.
Only in the case you have control of both pages, you can use https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage to safely send messages like this:
On you main site(one that loads the iframe):
const iframe = document.querySelector('#frame-id');
iframe.contentWindow.postMessage(/*any variable or object here*/, 'https://iframe-site.example.com');
on the iframe site:
// Called sometime after postMessage is called
window.addEventListener("message", (event) => {
// Do we trust the sender of this message?
if (event.origin !== "http://your-main-site.com")
return;
...
...
});

Yes, it's possible although cumbersome. You would need to print/echo the HTML of the page into the body of your page then apply a CSS rule change function. Using the same examples given above, you would essentially be using a parsing method of finding the divs in the page, and then applying the CSS to it and then reprinting/echoing it out to the end user. I don't need this so I don't want to code that function into every item in the CSS of another webpage just to aphtply.
References:
Printing content of IFRAME
Accessing and printing HTML source code using PHP or JavaScript
http://www.w3schools.com/js/js_htmldom_html.asp
http://www.w3schools.com/js/js_htmldom_css.asp

Related

Dynamically load stylesheets

i know that you can have style-sheets in the head of a page, but i like to have them in a separate file. Now i'm working with a single page application.
Well in an SPA the content is dynamic, right? so i didn't want to import all the style-sheets in the head section with the link tag. Can i somehow import style-sheets as-and-when i need them?
I mean, can i have a link in the body, such that whenever my SPA loads some dynamic content, a style sheet also gets loaded? Such that i dont have to load all the stylesheets even when the dynamic content is not loaded..
I stress again: Whenever the content loads, the styles load.
I know i can do it with the help of an inline style like this:
~PSEUDO CODE
<tagname style="somestyle"></tagname>
but can i have some dynamic file imports too? Can i have the link tag in the body too? Even if it works, is it standard?
You should look into asychronously loading assets, such as the famous google-analytics code. You can load external stylesheets using Javascript.
JavaScript
(function(){
var styles = document.createElement('link');
styles.rel = 'stylesheet';
styles.type = 'text/css';
styles.media = 'screen';
styles.href = 'path/to/css/file';
document.getElementsByTagName('head')[0].appendChild(styles);
})();
Lines 1 and 7 create a new scope for variables such that local variables do not collide or override with globally scoped variables. It isn't necessary just a best practice. This solution also assumes you have a <head> tag in your html.
You can add/remove/edit link tags in your head area with java script to add/remove stylesheet files.
Code example:
Add a stylesheet to the head:
var newstyle = document.createElement("link"); // Create a new link Tag
// Set some attributes:
newstyle.setAttribute("rel", "stylesheet");
newstyle.setAttribute("type", "text/css");
newstyle.setAttribute("href", "filename.css"); // Your .css File
document.getElementsByTagName("head")[0].appendChild(newstyle);
To remove or edit a stylesheet you can give every stylesheet an id attribute and access it with this:
document.getElementById('styleid')
Or you can loop through all link tags in the head area and find the correct one but I suggest the solution with the ID ;)
Now you can change the href attribute:
document.getElementById('styleid').setAttribute("href", "newfilename.css");
Or you can remove the complete tag:
var styletorem = document.getElementById('styleid');
styletorem.parentNode.removeChild(styletorem)
I just tried to give dynamic styling to my webpage. I used a button. On click of it, the CSS will get imported using a method in Javascript.
In my html, I have:
<button type="button" onclick="changeStyle()"> CLICK TO SEE THE MAGIC!! </button>
Then in Javascript, I have a method named changeStyle():
function changeStyle()
{
var styles = document.createElement('link');
styles.type="text/css";
styles.rel="stylesheet";
styles.href="./css/style.css";
document.head.appendChild(styles);
}
It worked perfectly.

Binding to events on parent page from iframe [duplicate]

I have an iframe and in order to access parent element I implemented following code:
window.parent.document.getElementById('parentPrice').innerHTML
How to get the same result using jquery?
UPDATE: Or how to access iFrame parent page using jquery?
To find in the parent of the iFrame use:
$('#parentPrice', window.parent.document).html();
The second parameter for the $() wrapper is the context in which to search. This defaults to document.
how to access iFrame parent page using jquery
window.parent.document.
jQuery is a library on top of JavaScript, not a complete replacement for it. You don't have to replace every last JavaScript expression with something involving $.
If you need to find the jQuery instance in the parent document (e.g., to call an utility function provided by a plug-in) use one of these syntaxes:
window.parent.$
window.parent.jQuery
Example:
window.parent.$.modal.close();
jQuery gets attached to the window object and that's what window.parent is.
You can access elements of parent window from within an iframe by using window.parent like this:
// using jquery
window.parent.$("#element_id");
Which is the same as:
// pure javascript
window.parent.document.getElementById("element_id");
And if you have more than one nested iframes and you want to access the topmost iframe, then you can use window.top like this:
// using jquery
window.top.$("#element_id");
Which is the same as:
// pure javascript
window.top.document.getElementById("element_id");
in parent window put :
<script>
function ifDoneChildFrame(val)
{
$('#parentPrice').html(val);
}
</script>
and in iframe src file put :
<script>window.parent.ifDoneChildFrame('Your value here');</script>
yeah it works for me as well.
Note : we need to use window.parent.document
$("button", window.parent.document).click(function()
{
alert("Functionality defined by def");
});
It's working for me with little twist.
In my case I have to populate value from POPUP JS to PARENT WINDOW form.
So I have used $('#ee_id',window.opener.document).val(eeID);
Excellent!!!
Might be a little late to the game here, but I just discovered this fantastic jQuery plugin https://github.com/mkdynamic/jquery-popupwindow. It basically uses an onUnload callback event, so it basically listens out for the closing of the child window, and will perform any necessary stuff at that point. SO there's really no need to write any JS in the child window to pass back to the parent.
There are multiple ways to do these.
I) Get main parent directly.
for exa. i want to replace my child page to iframe then
var link = '<%=Page.ResolveUrl("~/Home/SubscribeReport")%>';
top.location.replace(link);
here top.location gets parent directly.
II) get parent one by one,
var element = $('.iframe:visible', window.parent.document);
here if you have more then one iframe, then specify active or visible one.
you also can do like these for getting further parents,
var masterParent = element.parent().parent().parent()
III) get parent by Identifier.
var myWindow = window.top.$("#Identifier")

Changing content of iframe dynamicallly

I have a bit different task to do,
first, i have add an iframe tag dynamically, which i was able to do easily using the code->
function getFrame()
{
var iframeTA = document.createElement("IFRAME");
iframeTA.setAttribute("src", "iframeTakeAction.html");
iframeTA.style.width = "200px";
iframeTA.style.height = "200px";
document.getElementById("status").appendChild(iframeTA);
}
now, want i want to do is to access the elements of iframeTA (i.e. elements within the body tag of 'iframeTakeAction.html' which is the source of iframeTA),
something like this ->
iframeTA.body.getSomeElement......
Hope this kind of operation is possible, if so please put some light.
Thanks.
You should be able to access it with:
document.getElementById("TOUR IFRAME ID")
However, this only holds as long as your iframe src is a relative path on the same domain. If you change the domain then your browser will prevent you to do this.

Is there a way to set the CSS information for a particular instance of YUI DataTable?

The place were I wnat to use the YUI DataTable is in a wiki that allows HTML and javascript. I have created the custom table, put it in a div and gave it an ID and it works really well except that it usees the CSS from the container wiki page and visually it is not presentable. I would like to be able to set the CSS information for this particular table so that it is more readable. As you might guess I cannot modify the "head" information as the wiki only allows me to add things to the "body" of the html. I am by no means an expert in html and as such I am not sure if can specify CSS for a one table?
I was looking around in the YUI documentation to see if there was a mechansim in the YUI DataTable to set the CSS type of information but I could not really find anything. It seems like I should be able to set it in the oConfig object I pass to the table when it is created. So if someone knows of a way to do it using the YUI DataTable parameters that would be appreciated as well.
Can you run Javascript in the page? If so, then you can dynamically add a css link to the page without access to the element.
Here's how from the open source Timeline project:
// Use document for the doc param
function includeCssFile(doc, url) {
if (doc.body == null) {
try {
doc.write("<link rel='stylesheet' href='" + url + "' type='text/css'/>");
return;
} catch (e) {
// fall through
}
}
var link = doc.createElement("link");
link.setAttribute("rel", "stylesheet");
link.setAttribute("type", "text/css");
link.setAttribute("href", url);
getHead(doc).appendChild(link);
};
function getHead(doc) {
return doc.getElementsByTagName("head")[0];
};
Put your datatable in a specific div with an id
Or: Via the css selector : #yourdivid .yui-dt-data

<iframe> - How to show the whole height of referenced page?

I have an application that I would like to embed inside our companies CMS. The only way to do that (I am told), is to load it in an <iframe>.
Easy: just set height and width to 100%! Except, it doesn't work.
I did find out about setting frameborder to 0, so it at least looks like part of the site, but I'd prefer not to have an ugly scrollbar inside a page that allready has one.
Do you know of any tricks to do this?
EDIT: I think I need to clarify my question somewhat:
the company CMS displays the fluff and stuff for our whole website
most pages created through the CMS
my application isn't, but they will let me embedd it in an <iframe>
I have no control over the iframe, so any solution must work from the referenced page (according to the src attribute of the iframe tag)
the CMS displays a footer, so setting the height to 1 million pixels is not a good idea
Can I access the parent pages DOM from the referenced page? This might help, but I can see some people might not want this to be possible...
This technique seems to work (gleaned from several sources, but inspired by the link from the accepted answer:
In parent document:
<iframe id="MyIFRAME" name="MyIFRAME"
src="http://localhost/child.html"
scrolling="auto" width="100%" frameborder="0">
no iframes supported...
</iframe>
In child:
<!-- ... -->
<body>
<script type="text/javascript">
function resizeIframe() {
var docHeight;
if (typeof document.height != 'undefined') {
docHeight = document.height;
}
else if (document.compatMode && document.compatMode != 'BackCompat') {
docHeight = document.documentElement.scrollHeight;
}
else if (document.body
&& typeof document.body.scrollHeight != 'undefined') {
docHeight = document.body.scrollHeight;
}
// magic number: suppress generation of scrollbars...
docHeight += 20;
parent.document.getElementById('MyIFRAME').style.height = docHeight + "px";
}
parent.document.getElementById('MyIFRAME').onload = resizeIframe;
parent.window.onresize = resizeIframe;
</script>
</body>
BTW: This will only work if parent and child are in the same domain due to a restriction in JavaScript for security reasons...
You could either just use a scripting language to include the page into the parent page, other wise, you might want to try one of these javascript methods:
http://brondsema.net/blog/index.php/2007/06/06/100_height_iframe
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_22840093.html
Provided that your iframe is hosted on the same server as the containing page, you can access it via javascript.
There are a number of suggested methods for setting the iframe to the full height of the contents, each with varying degrees of success - a google for this problem shows that it's quite a common one, with no real, one-size-fits-all consensus solution i'm afraid!
Several people have reported that this script does the trick, but may need some modification for your specific case (again, assuming your iframe and parent page are on the same domain).
I might be missing something here, but adding scrolling=no as an attribute to the iframe tag normally gets rid of the scrollbars.