Iframe does not trigger resize event - javascript

After 3 days of research and trial and error, I am not able to get the iframe nor its contents to trigger a resize event so that my resize function is called. If I use ...trigger("resize"); to manually trigger a resize event, my resize function is called and works. The page that is loaded in the iframe is on the same domain (http://localhost:81/curlExample/) as the page containing the iframe. Eventually, the page in the iframe will be a supplied by the php curl method, but I would like to get it working first.
*******Updated********
How do I get the resize event triggered when I resize the browser window which causes the iframe to adjust its size?
Thank you for your help!
Page with the iframe
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
function setResize()
{
window.alert("Hello");
var iframeRef = document.getElementById('displayframe');
$(iframeRef).on("resize", function(){
var xExp = 0;
window.alert("Resize event fired.");
});
}
$('#displayframe').load(function()
{
alert("Hello from iFrame. Load event fired.");
var myStallTime = setTimeout(setResize, 3000);
});
});
</script>
</head>
<body>
<p id="myP">Hello</p>
<iframe id="displayframe" src="http://localhost:81/curlExample/HelloIframe.xhtml" style="height:250px; width:100%;">
<p>Your browser does not support iframes.</p>
</iframe>
</body>
</html>
Page within the iframe (HelloIframe.xhtml)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>TODO supply a title</title>
</head>
<body>
<div id="myContent" style="width:100%; height:200px;">
<h1>TODO write content</h1>
<h2>Extremity sweetness difficult behaviour he of</h2>
<p>Agreed joy vanity regret met may ladies oppose who. Mile fail as left as hard eyes. Meet made call in mean four year it to. Prospect so branched wondered sensible of up. For gay consisted resolving pronounce sportsman saw discovery not. Northward or household as conveying we earnestly believing. No in up contrasted discretion inhabiting excellence. Entreaties we collecting unpleasant at everything conviction.</p>
<p>Yet remarkably appearance get him his projection. Diverted endeavor bed peculiar men the not desirous. Acuteness abilities ask can offending furnished fulfilled sex. Warrant fifteen exposed ye at mistake. Blush since so in noisy still built up an again. As young ye hopes no he place means. Partiality diminution gay yet entreaties admiration. In mr it he mention perhaps attempt pointed suppose. Unknown ye chamber of warrant of norland arrived.</p>
</div>
</body>
</html>

The <iframe> element will never trigger a resize event, like an <img> or a <div>. You must get this event from window. As your iframe document comes from the same origin as the parent document, you can access its contentWindow and any other attribue.
So, try this:
var iframeWin = document.getElementById('displayframe').contentWindow;
$(iframeWin).on('resize', function(){ ... });
I did it using only DOM's addEventListener.
var iframeWin = document.getElementById('displayframe').contentWindow;
iframeWin.addEventListener('resize', function(){ ... });

Related

IE9 Bug? <script> content executed twice when using Node.cloneNode(true)

I know IE9 is kind of old now, but it is the lowest version of IE that I still must support in a Web application I'm building.
Anyway, while doing some DOM manipulation and testing in different browsers, I noticed that IE9 was doing something very strange. I had a <script> block in a DIV element, and when I deep-cloned that DIV element using Node.cloneNode(true), and attached the clone to the document somewhere using document.body.appendChild or document.body.insertBefore, the cloned <script> block would get executed again! No other browser exhibits this behavior.
If I'm not mistaken, <script> blocks aren't supposed to be executed when appended to the document after the document has initially loaded, am I right? If I'm correct, is this a bug in IE9?
Here is a simple HTML document where you can see this behavior in action. Create an HTML document with this code and load it up in Internet Explorer using IE9 emulation. You should see an alert popup that says "hey". Next, click the "Click Me" button, and you will see the same popup get executed again!
<!DOCTYPE html>
<html>
<head>
<title>IE9 Script Tag Bug Test</title>
<script>
function ButtonClick(){
var Elem = document.getElementById('mydiv');
var ElemClone = Elem.cloneNode(true);
document.body.insertBefore(ElemClone,Elem);
}
</script>
</head>
<body>
<div id="mydiv">
This is a DIV.
<script>
alert("hey");
</script>
</div>
<button onclick="ButtonClick();">Click Me</button>
</body>
</html>

what does "JavaScript sanitization doesn't save you from innerHTML" mean?

I'm learning xss prevention through this ppt:http://stash.github.io/empirejs-2014/#/2/23, and I have a question on this page.
It says "JavaScript sanitization doesn't save you from innerHTML", and I tried a simple test like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<div id="test"></div>
<script>
var userName = "Jeremy\x3Cscript\x3Ealert('boom')\x3C/script\x3E";
document.getElementById('test').innerHTML = "<span>"+userName+"</span>";
</script>
</body>
</html>
when I opened this html on my browser(chrome), I only saw the name "Jeremy",by using F12, I saw
<div id="test"><span>Jeremy<script>alert('boom')</script></span></div>
Although the script had been added to html, the alert box didn't come out.
"JavaScript sanitization doesn't save you from innerHTML" I think this means that the word "boom" should be alerted. Am I right?
According to MDN, innerHTML prevents <script> elements from executing directly1, which means your test should not alert anything. However, it does not prevent event handlers from firing later on, which makes the following possible:
var name = "\x3Cimg src=x onerror=alert(1)\x3E";
document.getElementById('test').innerHTML = name; // shows the alert
<div id="test"></div>
(script adapted from the example in the article, with escape sequences although I'm not sure those are relevant outside of <script> elements)
Since <script> elements never execute when inserted via innerHTML, it's not clear to me what that slide is trying to convey with that example.
1 This is actually specified in HTML5. MDN links to a 2008 draft; in the current W3C Recommendation, it's located near the end of section 4.11.1, just before section 4.11.1.1 begins:
Note: When inserted using the document.write() method, script elements execute (typically synchronously), but when inserted using innerHTML and outerHTML attributes, they do not execute at all.

Load all iframes on blog asynchronously

I run a blog that features lots of videos and other framed content.
a typical blogpost body i pull from my database looks like this:
<p>some text</p>
<iframe src="http://example.com" width="400" height="300"></iframe>
<p>some text</p>
some posts have 2-3 iframes in them - the starting-page usually features 6-7 iframes.
i'd like to speed up the loading-time of my blog - is there a way i can make all iframes on my starting-page load asynchronously?
I'll suggest you to have all your data with you and identify the iframes to load and use setTimeout to load different set of iframes with some time gap.
As someone said in a comment, iframes load asynchronously. Perhaps what you're experiencing is a slow load of the main page while it is also loading the iframes contents. I would suggest using this technique:
<!DOCTYPE html>
<html>
<head>
<title>speedup page with iframes</title>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
some content
<br>
some other content
<br>
<iframe id="data_a"></iframe>
<br>
some wild content appears
<br>
<iframe id="data_b"></iframe>
<br>
some wild content appears
<br>
<iframe id="data_c"></iframe>
<br>
the end
<script>
$(function(){
//the iframes will only load AFTER your
//main page is fully loaded
$("#data_a").attr("src", "http://domain1.com/some/path/news.html");
$("#data_b").attr("src", "http://domain2.com/gallery/pictures.html");
$("#data_c").attr("src", "http://domain3.com/contact/map.html");
});
</script>
</body>
</html>
I hope this helps!
So, i read a lot about this topic in the last few days. Especially this article was helpful, since it discusses the actual problem I was facing: a belated onload() event that fires after all iframes are loaded.
After all, what I came up with are these lines of jQuery-Code that seems to work for me:
var src = new Array();
$(function(){
// onDomReady() store all iframe sources in array
$('iframe').each(function(){
src.push($(this).attr('src'));
$(this).attr('src', '');
});
});
$(window).load(function() {
// onload() restore all iframe sources from the array
var i = 0;
$('iframe').each(function(){
$(this).attr('src', src[i]);
i++;
});
});
So here's the deal: I tried a couple of times with and without this code and measured DomReady and Load events.
The DomReady event fires around the same time (before: 1.58s, after: 1.60s)
The Load event on the other hand fires waaay earlier (before: 8.19s, after: 1.92s)
In a way, this doesn't actually improve loading-speed, of course - anyway, in my opinion. the user experience is improved. Any comments or suggestions?

JavaScript onLoad resize

I'm fairly new to programing, especially javascript. I have created what I am regarding as an net-art project that refreshes a browser and cycles through a series of images. I want the browser window to automatically resize to the dimensions of the images, 612x612 px. I've tried everything I can think of, everything I've come across on the web, and nothing seems to work with the code I have set up for the refresh and image load. I need assistance.
Let me say that I am normally against such unser unspecified browser resizes or any intrusive script that doesn't allow the user to make that decision on his/her own. But this is an art project and will only exist as part of a gallery on my own website and the user will be warned ahead of time, before clicking the link, that their browser will resize.
What I want is for the browser to resize to the specified dimensions when the page loads, then cycle through the images, via the automatic refresh.
So please, anyone who would be willing to offer their assistance with this I would be very very grateful. I've gotten pretty far I think and this resize is the last little bit of the puzzle. Thank you in advance.
You can see the rough project with no resize here: http://jasonirla.com/bgchange%202/
and the code I'm using:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="title" content="Background Change" />
<meta name="description" content="Background Change" />
<title>Everyday Sky</title>
<script type="text/javascript">
// auto refresh window PT 1
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}
// no. of images in folder is 43
var totalCount = 43;
// change image on refresh
function ChangeIt() {
var num = Math.ceil( Math.random() * totalCount );
document.body.background = 'images/'+num+'.jpeg';
}
</script>
</head>
<!-- Refresh PT 2 with timer in seconds 5000=5seconds-->
<body onload="JavaScript:timedRefresh(100);">
<script type="text/javascript">
ChangeIt();
</script>
<style type="text/css">
body {
background-repeat: no-repeat;
}
</body>
</html>
It's true, you can only set the size of a browser window by creating a new window with JavaScript but many security settings will block pop-up windows. I think it's bad UI design to do what you're attempting anyway. If you really want something modern and highly functional, Lightbox (as mentioned above) is a great tool as well as the dialog box in the jQuery UI.
Since this for an exhibition, you will choose what browser to use but most new browsers dont let JavaScript resize them anymore. Worth a try, though.
<body onload="JavaScript:timedRefresh(100);resizeTo(500,500);self.moveTo(640,10);>
....
</body>
Cheers.

using a small model to test asynchronous processing

I've received much excellent instruction on Stack Overflow, especially regarding my feeble attempts to incorporate asynchronous processing in a recent web application. To narrow down some issues to their minimum, I created a very small HTML/javascript page to play with getJSON and look at some behavior mentioned by jfriend00. So far as I can see, this is a legitimate program, but although IE9 runs it, FireFox emits some text, then hangs/infinitely loops/whatever, while Chrome shows only the H1 (FireFox declined to do so) and the last string. Obviously, there is something horribly wrong with this code and I'm not seeing it. How about you?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
</head>
<body>
<h1>testing 2</h1>
<script type="text/javascript">
function buildTree() {
$.getJSON('MurakiMaida.json', function(data) {
document.write("how about here?<br>");
$.each(data.person, function(i, xdata) {
document.write(xdata.id + "<br>");
});
});
document.write("<br>what are we doing here?");
}
buildTree();
</script>
</body>
</html>
document.write is probably the culprit.
I don't understand what exactly you are try to do, but document.write should only be used while the page is loading. Actually it is probably better to never use it.*
Create a <div id='foo'/> and write to it such as $('#foo').append($("<div>"+xdata.id+"</div>")
document.write was the way to use Javascript to add HTML to a document back in the days before the DOM existed. It still exists for backward compatibility, but should be avoided.

Categories