I have a page that contains an iframe that gets loaded using Javascript:
index.html
<iframe id="myFrame" width="800" height="600" style="display: none;"></iframe>
<div id="loader"><!-- some loading indicator --></div>
<script type="text/javascript">
function someFunction() {
var myFrame = document.getElementById('myFrame');
var loader = document.getElementById('loader');
loader.style.display = 'block';
myFrame.src = 'myFrame.html';
myFrame.onload = function() {
myFrame.style.display = 'block';
loader.style.display = 'none';
};
}
</script>
The page that gets loaded in the iframe contains some Javascript logic which calculates the sizes of certain elements for the purposes of adding a JS driven scrollbar (jScrollPane + jQuery Dimensions).
myFrame.html
<div id="scrollingElement" style="overflow: auto;">
<div id="several"></div>
<div id="child"></div>
<div id="elements"></div>
</div>
<script type="text/javascript">
$(document).load(function() {
$('#scrollingElement').jScrollPane();
});
</script>
This works in Chrome (and probably other Webkit browsers), but fails in Firefox and IE because at the time jScrollPane gets called, all the elements are still invisble and jQuery Dimensions is unable to determine any element's dimensions.
Is there a way to make sure my iframe is visible before $(document).ready(...) gets called? Other than using setTimeout to delay jScrollPane, which is something I definitely want to avoid.
Some browsers assume that when "display:none" is applied to replaced elements (like Flash or an iframe) the visual info for that element is no longer needed. So, if the element is later displayed by the CSS, the browser will actually recreate the visual data form scratch.
I imagine that having the iframe default to "display:none;" makes the browser skip the rendering of the HTML so the tags don't have any dimensions. I would set the visibility to "hidden" or position it off the page rather than use "display:none;".
Good luck.
instead of making the iframe invisible by using display:none, you could try to...
... set visibility:hidden
... set position:absolute; top:-600px;
... set opacity:0
or something else that makes jQuery "see" the objects but not the user (and reset the used css-attributes in your myFrame.onload function).
visibility:collapse;
display:hidden;
height:0px;
Will work to get rid of white space too..
The iframe will also load..
Hidden iframes are a huge security issue. Probably best to try to find another way to accomplish what you want, if it is legitimate, because hopefully future browsers will get rid of this feature altogether. http://blog.opendns.com/2012/07/10/opendns-security-team-blackhole-exploit/
Related
I have this function to print a DIV.
Whenever the page is loaded and I click in a "Print" link I have, the DIV is shown to be printed without CSS.
If I close Chrome's print visualization page and click in the "Print" link again, the DIV has CSS applied.
Any ideas why?
Javascript
function printDiv(divId) {
var printDivCSSpre =
'<link href="/static/assets/vendor/sb-admin-2-1.0.7/bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">' +
'<link href="/static/assets/vendor/sb-admin-2-1.0.7/dist/css/sb-admin-2.css" rel="stylesheet">' +
'<div style="width:1000px; padding-right:20px;">';
var printDivCSSpost = '</div>';
$('body').append('<iframe id="print_frame" name="print_frame" width="0" height="0" frameborder="0" src="about:blank"></iframe>');
$("link").clone().appendTo($("#print_frame").contents().find("head"));
window.frames["print_frame"].document.body.innerHTML =
printDivCSSpre + document.getElementById(divId).innerHTML + printDivCSSpost;
window.frames["print_frame"].window.focus();
var windowInstance = window.frames["print_frame"].window;
windowInstance.print();
}
HTML
<a id="print" href="#">
<i class="fa fa-print"></i> Print
</a>
<script>
$('#print').click(function () {
printDiv('report')
})
</script>
<div id="report" class="report">
<p># Generated Table#</p>
</div>
First click:
http://imgur.com/a/Go81Y
Closing the print preview page and clicking again in print
http://imgur.com/a/SCxJF
This happens because when you call your printDiv() function, css is also written using inner HTML and in this scenario CSS is not applied during first click because you wrote CSS to the elements even when they do not exist inside DIV.
The function to work as desired has to write DIV contents first and then CSS should be applied. I would say write css after contents of DIV or load on top of your HTML page and just write DIV contents.
Hope that helps.
Every thing is right just change the sequence. In browser debugger on first click it didn't show 'print_frame' in sources section while in second click it does (I am using chrome devtool).
So load in memory frame with css attributes during onload:
var windowInstance;
$(function(){
$('body').append('<iframe id="print_frame" name="print_frame" width="0" height="0" frameborder="0" src="about:blank"></iframe>');
$("link").clone().appendTo($("#print_frame").contents().find("head"));
windowInstance = window.frames["print_frame"].window;
});
and onClick just append html
$('#print').click(function () {
var divId = 'report';
var printDivCSSpre ='<div id="printReportDiv" style="width:1000px; padding-right:20px;">';
var printDivCSSpost = '</div>';
window.frames["print_frame"].document.body.innerHTML = printDivCSSpre + document.getElementById(divId).innerHTML + printDivCSSpost;
window.frames["print_frame"].window.focus();
windowInstance.print();
});
updated jsfiddle
Try this one. The problem mainly arises because the css has not been applied to the page when the print command is initiated. setTimeout is one way to solve it as others have mentioned but it is really not possible to predict how much delay you will need. Slow internet connections will require high delays before you fire the print statement. The following code, however, only fires the print event after the css has been properly applied to the iframe.
$('#print').click(function () {
if($("#print_frame").length == 0) {
$('#report').after('<iframe id="print_frame" name="print_frame" width="0" height="0" frameborder="0" src="about:blank"></iframe>');
}
var $head = $("#print_frame").contents().find("head");
// for now for ease I will just empty head
// ideally you would want to check if this is not empty
// append css only if empty
$head.empty();
$.ajax({
url : "https://dl.dropboxusercontent.com/u/7760475/reports.css",
dataType: "text",
success : function (reports) {
// grab css and apply its content to the iframe document
$head.append('<style>'+reports+'</style>');
$.ajax({
url : "https://dl.dropboxusercontent.com/u/7760475/bootstrap.css",
dataType: "text",
success : function (bootstrap) {
// grab another css and apply its content to the iframe document
// there may be better ways to load both css files at once but this works fine too
$head.append('<style>'+bootstrap+'</style>');
// css has been applied
// clone your div and print
var $body = $("#print_frame").contents().find('body');
// empty for ease
// but later append content only if empty
$body.empty();
$("#report").clone().appendTo($body);
$('#print_frame').get(0).contentWindow.print();
}
});
}
});
});
Use inline CSS instead.
Reason: When we PRINT or save as PDF if fails to fetch external css Files, So we have to use Inline css.
edited your file please see: jsfiddle.net/ytzcwykz/18/
As other people mentioned it is hard to see your problem without seeing the working example of a problem, but just guessing from the code:
Browser is not able to load the CSS before your print() call.
Browser is not able to render the CSS before your print() call.
Keeping that in mind changing your JS function that way might do the trick
function printDiv(divId) {
$("link").clone().appendTo($("#print_frame").contents().find("head"));
window.frames["print_frame"].document.body.innerHTML =
printDivCSSpre + document.getElementById(divId).innerHTML + printDivCSSpost;
window.frames["print_frame"].window.focus();
var windowInstance = window.frames["print_frame"].window;
setTimeout(function() {
windowInstance.print();
}, 0);
}
The idea behind this function is to let browser execute it's code after we added changed the HTML/CSS code in the window - see Why is setTimeout(fn, 0) sometimes useful?
WARNING: this approach is not tested for your particular problem, and it might also not work because we escape/leave the mouse-click call-stack, calling print() method might be not possible out of user-interaction stack.
UPDATE: after looking in the posted jsfiddle - my assumption was correct, the browser needs some time to load and render the CSS, that is why calling the print() right after changing iframe contents doesn't give the desired result. There are 3.5 ways to solve that:
Use events to identify when iframe's document and window has finished loading and rendering. I tried two approaches, and failed so far, need to read docs more carefully about when document and window are behiving during the loading sequence:
we can do that from outside of iframe, i.e. listen to events of iframe element and it's children
we can do that from inside of iframe, i.e. add little javascript snippet inside which will send a message to the parent window when loading is done.
Consider forming the print result different, how about print style-sheets? I.e. add one more style sheet with print-media query to the parent doc and just call print on it?
Consider forming an iframe which is already loaded and ready to be printed, but replace just the table contents inside it.
As others mentioned, The problem here is that the CSS files used are external resources and browser takes time to download and cache it locally. Once it is cached, it would serve faster and that's why it works fine from the second click.
As Anton mentioned, setTimeout is the key here! You may probably increase the timeout seconds to make that work. I tried setting it to 500ms and that worked,
setTimeout(function(){windowInstance.print();},500);
I dispose of the following code :
<!DOCTYPE html>
<body>
<a id="toto" contenteditable="true">Button</a>
</body>
<script>
var elt= document.getElementById('toto');
elt.focus();
</script>
</html>
When the page is loaded, the cursor is already in place and you just have to type what you want. The trouble is that it doesn't work with IE11.
Since this works with other tags like <div>, I assume I just have to make <a> focusable for IE. Any ideas how ?
There are two issues here. First, IE automatically focuses on the body element after the page has loaded. So if your code is exactly as in the question, it will set focus on the a element but this will be overridden a few nanoseconds later, after the load event is triggered. A simple way to avoid this is to make sure the focus is set only after load. Example:
<a id="toto" contenteditable="true">Button</a>
<script>
window.onload = function() {
var elt= document.getElementById('toto');
elt.focus();
}
</script>
But IE also seems to have an issue with setting focus on an a element without an href attribute. Whatever the cause might be, you can circumvent this a) by adding href="javascript:;", but this is awkward and causes link formatting to be applied, or b) by changing the a element to e.g. a span element;
In order to prevent an iframe from flashing, I'm setting its visibility inside a setTimeout (the CSS is set to visibility:hidden)
setTimeout(function(){
$n('#myFrame').css('visibility','visible');}, 750);
Works great, although when I load subsequent locations inside the frame, the flashing behavior returns since the visibility is already set.
What I'd like to do is create a function that targets the iframe BEFORE the DOM/page has loaded to set the visibility to hidden again and then setTimeout.
Keep in mind that this script will run on the ServiceNow platform, meaning some options are limited (can't load in document head, etc.)
It's sort of like a reverse document.ready(). Is this even possible?
Thanks for any leads,
Paco
Just set it in your source:
<iframe style="display: none;"></iframe>
Then un-hide it when you want to.
$('buttonToChangeTheIframePage').click(function(e){
e.preventDefault();
$('#myFrame').css('visibility','hidden');
$('#myFrame').delay(1000).css('visibility','visible');
});
This assumes you are loading locations from OUTSIDE the iframe - anything within the iframe (like a link) will still trigger this behaviour.
EDIT
This is actually better and will work for all circumstances (I think - just check no silly errors as not tested)
<iframe id="myFrame" src="http://www.google.com/" onLoad="hideUnhide();"></iframe>
function hideUnhide(){
$('#myFrame').css('visibility','hidden').delay(1000).css('visibility','visible');
}
Use addAfterPageLoadedEvent(func) in js_include_doc_type.js
<iframe id="gsft_main" style="visibility: hidden;">
anything ....
<script>
addAfterPageLoadedEvent(function() {
$j('#gsft_main').css('visibility','visible');
});
</script>
</iframe>
I am using iframe popup and i want to change something outside of iframe with jquery from iframe ?
this need to be done with jquery.
code like this
<iframe> <div id="change">Change css</div> </iframe>
<div class="outer-div"> Text goes here </div>
<script>
$("#change").live('click', function(){
$('#outer-div').css('display','none');
});
<script>
i want to hide of outer div click on iframe inner div
thanks
Simranjeet singh
This is some code that has worked for me.
Assuming that the iFrame is within the same domain as it's parent, try this:
// -- Find the PARENT of the iFrame that this script runs in
var $topLevel = $(window.parent.document, window.parent.document);
If you then use $topLevel as a starting point for your jQuery it should work.
Be aware that this codes works alright in modern browsers but doesn't seem to operate in IE8 (and untested below IE8)
Is it possible to disable/restrict iframe reloading?
the problem is: When I use jquery to detach/append iframe it reloads.
i = $('#i') //<iframe id="i" src="..."></iframe>
p = i.parent()
i.detach()
i.appendTo(p)
So, after I do i.appendTo(p), ifram's content is reloaded
I had the same problem trying to defer ads loading. I think it is not possible to fix.
The only way that I found was to change the absolute position on css.
i.e:
var $i = $('#i'), $t = $('#target');
$i.css({position:'absolute',top:$t.offset().top, left:$t.offset().left});
Maybe you will need to add z-index and size properties too. It will depends of your design.