Update iframe body color after load - javascript

I have a page ,page1.html that loads page2.html via an iframe . I need to change the body color of the iframe page (page2.html) to override the CSS style that's loaded on page2.html.
(both pages are on same domain). How can that be updated via Javascript ?

A bit of googling turn up this:
Scripting IFrames
It suggests window.frames[iframeName].document should work.

Since both pages lives on the same domain it should be easy.
Try this,
var changeIFrameBodyColor = function()
{
var iFrame = document.getElementById('iFrame');
var iFrameBody;
if ( iFrame.contentDocument )
{ // DOM
var iFrameBody = iFrame.contentDocument.getElementdByTagName('body')[0];
}
else if ( iFrame.contentWindow )
{ // IE
var iFrameBody = iFrame.contentWindow.document.getElementdByTagName('body')[0];
}
iFrameBody.style.color = '#ff0000';
}
Change Color
<iframe id="iFrame" src="page2.html" ../>

Related

Iframe with height based on page content height

in my Wordpress site I use a plugin that allows me to view external pages in an iframe that changes its height based on the height of the content.
The page I try to load in the iframe is a simple html page that calls a javascript.
This however prevents the iframe from changing its height.
Can it be solved in any way?
Thanks.
Here is the code of the html page that must be loaded into the iframe:
<body>
<script type="text/javascript" src="https://www.domain-name.com/script-name.php?param1=1&param2=22"></script>
</body>
give div ID or Call and the CSS
height : 100vh ;
try this code on load
function resizeIFrameToFitContent( iFrame ) {
iFrame.width = iFrame.contentWindow.document.body.scrollWidth;
iFrame.height = iFrame.contentWindow.document.body.scrollHeight;
}
window.addEventListener('DOMContentLoaded', function(e) {
var iFrame = document.getElementById( 'iframe_block' );
resizeIFrameToFitContent( iFrame );
// or, to resize all iframes:
var iframes = document.querySelectorAll("iframe");
for( var i = 0; i < iframes.length; i++) {
resizeIFrameToFitContent( iframes[i] );
}
} );

Get parent of clicked tag inside of iframe

I've an iframe that contain an HTML page.Now I want to get class of the parent item that clicked.
this is my ifram:
<iframe src="//example.com" id="frame" ></iframe>
this is css:
#frame{ width:380px; height:420px;}
this is my script:
$(document).ready(function() {
var iframe = document.getElementById('frame');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document.body;
$(innerDoc).on('click', function(e) {
var thisID = ((e.target).id);
alert(thisID);
alert(innerDoc.getElementById(thisID));
$(thisID).click(function() {
var Allclassnames = $(thisID).parent();
console.log(Allclassnames);
});
});
});
but it return the item was clicked only.how to fix it?
Demo:DEMO
NOTE:these are in a same domain.maybe below DEMO not worked for this reason.but I'm sure that my HTML is inside of the same domain with my web site.
thank you.
Add sandbox attributes to the iframe
<iframe src="/example.html" id="frame" sandbox="allow-scripts allow-same-origin"></iframe>
Change the script to
<script>
$('#frame').load(function() {
$('#frame').contents().on('click', function(e) {
var thisID = ((e.target).id);
alert(thisID);
alert($('#'+thisID,this));
$('#'+thisID,this).click(function() {
var Allclassnames = $(this).parent();
console.log(Allclassnames);
});
});
});
</script>
Make sure that every element in frame doc. have some id or else the alert() may throw an error.
To see the console message of iframe you need to change the scope from the scope dropdown , it's in console tab besides the filter icon in the chrome developer tools.
You cannot interact with the contents of an iframe unless it is on the same domain as the parent document.
See:
https://en.wikipedia.org/wiki/Same-origin_policy

Resize Cross Domain Iframe Height [duplicate]

This question already has answers here:
Resizing an iframe based on content
(26 answers)
How to get height of iframe cross domain
(2 answers)
Closed 2 years ago.
I'm trying to change the iframe height parameter to the same px of the page being loaded within the iframe. The page that's being loaded in the iframe is coming from another domain.
Different pages will be loaded up inside of the iframe causing the height of the iframe content to change, So I will need to grab the iframe content height and apply it to the iframe height parameter.
Here a example of what im talking about: http://jsfiddle.net/R7Yz9/3/
<div class="site">Amazon </div>
<div class="site">Cnn </div>
<div class="site">Wikipedia </div>
<iframe id="source" src="http://amazon.com/" frameborder="0" scrolling="no" width="100%" height="100%"></iframe>
.
$(document).ready(function() {
var iframe = $( "#source" );
$( "a[target=_top]" ).click( function(){
iframe.attr( "src", this.href );
return false;
});
});
It is only possible to do this cross domain if you have access to implement JS on both domains. If you have that, then here is a little library that solves all the problems with sizing iFrames to their contained content.
https://github.com/davidjbradshaw/iframe-resizer
It deals with the cross domain issue by using the post-message API, and also detects changes to the content of the iFrame in a few different ways.
Works in all modern browsers and IE8 upwards.
Minimum crossdomain set I've used for embedding fitted single iframe on a page.
On embedding page (containing iframe):
<iframe frameborder="0" id="sizetracker" src="http://www.hurtta.com/Services/SizeTracker/DE" width="100%"></iframe>
<script type="text/javascript">
// Create browser compatible event handler.
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
// Listen for a message from the iframe.
eventer(messageEvent, function(e) {
if (isNaN(e.data)) return;
// replace #sizetracker with what ever what ever iframe id you need
document.getElementById('sizetracker').style.height = e.data + 'px';
}, false);
</script>
On embedded page (iframe):
<script type="text/javascript">
function sendHeight()
{
if(parent.postMessage)
{
// replace #wrapper with element that contains
// actual page content
var height= document.getElementById('wrapper').offsetHeight;
parent.postMessage(height, '*');
}
}
// Create browser compatible event handler.
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
// Listen for a message from the iframe.
eventer(messageEvent, function(e) {
if (isNaN(e.data)) return;
sendHeight();
},
false);
</script>
You need to have access as well on the site that you will be iframing. i found the best solution here: https://gist.github.com/MateuszFlisikowski/91ff99551dcd90971377
yourotherdomain.html
<script type='text/javascript' src="js/jquery.min.js"></script>
<script type='text/javascript'>
// Size the parent iFrame
function iframeResize() {
var height = $('body').outerHeight(); // IMPORTANT: If body's height is set to 100% with CSS this will not work.
parent.postMessage("resize::"+height,"*");
}
$(document).ready(function() {
// Resize iframe
setInterval(iframeResize, 1000);
});
</script>
your website with iframe
<iframe src='example.html' id='edh-iframe'></iframe>
<script type='text/javascript'>
// Listen for messages sent from the iFrame
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent,function(e) {
// If the message is a resize frame request
if (e.data.indexOf('resize::') != -1) {
var height = e.data.replace('resize::', '');
document.getElementById('edh-iframe').style.height = height+'px';
}
} ,false);
</script>
If you have access to manipulate the code of the site you are loading, the following should provide a comprehensive method to updating the height of the iframe container anytime the height of the framed content changes.
Add the following code to the pages you are loading (perhaps in a header). This code sends a message containing the height of the HTML container any time the DOM is updated (if you're lazy loading) or the window is resized (when the user modifies the browser).
window.addEventListener("load", function(){
if(window.self === window.top) return; // if w.self === w.top, we are not in an iframe
send_height_to_parent_function = function(){
var height = document.getElementsByTagName("html")[0].clientHeight;
//console.log("Sending height as " + height + "px");
parent.postMessage({"height" : height }, "*");
}
// send message to parent about height updates
send_height_to_parent_function(); //whenever the page is loaded
window.addEventListener("resize", send_height_to_parent_function); // whenever the page is resized
var observer = new MutationObserver(send_height_to_parent_function); // whenever DOM changes PT1
var config = { attributes: true, childList: true, characterData: true, subtree:true}; // PT2
observer.observe(window.document, config); // PT3
});
Add the following code to the page that the iframe is stored on. This will update the height of the iframe, given that the message came from the page that that iframe loads.
<script>
window.addEventListener("message", function(e){
var this_frame = document.getElementById("healthy_behavior_iframe");
if (this_frame.contentWindow === e.source) {
this_frame.height = e.data.height + "px";
this_frame.style.height = e.data.height + "px";
}
})
</script>
There is no options in javascript to find the height of a cross domain iframe height but you can done something like this with the help of some server side programming. I used PHP for this example
<code>
<?php
$output = file_get_contents('http://yourdomain.com');
?>
<div id='iframediv'>
<?php echo $output; ?>
</div>
<iframe style='display:none' id='iframe' src="http://yourdomain.com" width="100%" marginwidth="0" height="100%" marginheight="0" align="top" scrolling="auto" frameborder="0" hspace="0" vspace="0"> </iframe>
<script>
if(window.attachEvent) {
window.attachEvent('onload', iframeResizer);
} else {
if(window.onload) {
var curronload = window.onload;
var newonload = function(evt) {
curronload(evt);
iframeResizer(evt);
};
window.onload = newonload;
} else {
window.onload = iframeResizer;
}
}
function iframeResizer(){
var result = document.getElementById("iframediv").offsetHeight;
document.getElementById("iframe").style.height = result;
document.getElementById("iframediv").style.display = 'none';
document.getElementById("iframe").style.display = 'inline';
}
</script>
</code>

Have to apply CSS from a hosting site through JavaScript

I have an iframe, and onLoad am applying css through javascript. This iframe contains data from website A and hosted on website B. The javascript that applies css will be included in the iframe and the css values (to change color of html elements) will be passed by website B.
I have written javascript and like this; please help if there are any suggestions to achieve this or any improvements will be appreciated.
The script on SiteA:-
/* this variable values will be set by site B */
JS
var iframeCSSParams = {
links: "blue",
companyName: "blue",
searchButtonColor: "darkcyan",
fontsColor: "blue"
so on..
};
function applycss(iframe, CSSParams) {
var linksColor = CSSParams.links;
var companyNameColor = CSSParams.companyName;
var searchButtonColor = CSSParams.searchButtonColor;
jQuery(iframe).contents().find('.alinks').css('color', linksColor);
jQuery(iframe).contents().find('.p-company-name').css('color', companyNameColor);
and so on...
}
function Iframe_Load(iframe) {
try {
var doc = iframe.contentDocument || iframe.contentWindow.document;
applycss(iframe, iframeCSSParams);
} catch (e) {
alert('exception: ' + e);
}
}
HTML
<iframe id="listFrame" scrolling="NO" style="padding:0; width:626px;" frameborder="0"
src="/siteA/search" onload="Iframe_Load(this)" />

How to load iframe content correctly in to <div in main page (same domain iframe)?

I got an ifram that has many links in it and i am trying to copy those link correctly to my main page. My current code copy the links incorectly .For example if the
actual hyper link is like this in iframe:
5
after coping it in to main page the hyper links become like this :
http://ok.mysite24.com/spring/./ok/doit.php
so after clicking to those links from within my main page i go to dead links instead of actual links. is there away to fix this problem by copying iframe content correctly or should i modify my iframe content ?
<script type='text/javascript'>
function getFrameContents(){
var iFrame = document.getElementById('myframe');
var iFrameBody;
if ( iFrame.contentDocument )
{ // FF
iFrameBody = iFrame.contentDocument.getElementsByTagName('body')[0];
}
else if ( iFrame.contentWindow )
{ // IE
iFrameBody = iFrame.contentWindow.document.getElementsByTagName('body')[0];
}
alert(iFrameBody.innerHTML);
document.getElementById('response').innerHTML = iFrameBody.innerHTML
}
</script>
<iframe id ='myframe' src='http://www.mysite.com/ok.php'></iframe>
<div id="response">
<p>getFrameContents! </p>
Before retrieving the innerHTML loop over all links and replace their DOM-href-attribute with their JS-href-property. This will turn the href-attributes into absolute URIs.
//clone the body to keep the original untouched
iFrameBody = iFrameBody.cloneNode(true);
var links = iFrameBody.getElementsByTagName('a');
for (var i = 0; i < iFrameBody.getElementsByTagName('a').length; ++i) {
if (links[i].hasAttribute('href')) {
links[i].setAttribute('href', links[i].href);
}
}
It looks like you want to resolve one relative address to the iframe's source address, which may also be relative. Psuedo code (ish):k
function resolveAddress(source, link) {
if(link.indexOf("../") == 0) {
index--; // go up one directory .//
return resolveAddress(source.substr(0,source.lastIndexOf("/")-1),
link.substr(1, link.length-1));
}
else if(link.indexOf("./") == 0) {
// reduce to current directory ./
return resolveAddress(source.substr(0,source.lastIndexOf("/"),
link.substr(2, link.length-1));
}
return source + link;
}
frame_src = "http://www.mysite.com/ok.php"
link = "./ok/doit.php";
resolveAddress(frame_src, link);
//=> "http://www.mysite.com/ok/doit.php"

Categories