Rectangle 27 2

Consider below as your window tree

Now in p1, keep function say pfunc, in which you code whatever you want to code

in I1 keep a function as below

function callParent()
   {
       parent.pfunc();
   }

in I2 on window onload call below function

function callParent()
{
   parent.callParent();
}

javascript - Onload function for an iframe inside another iframe - Sta...

javascript dom iframe frame
Rectangle 27 39

You can use the onload event to detect when the iframe has finished loading, and there you can use the scrollTo function on the contentWindow of the iframe, to scroll to a defined position of pixels, from left and top (x, y):

var myIframe = document.getElementById('iframe');
myIframe.onload = function () {
    myIframe.contentWindow.scrollTo(xcoord,ycoord);
}

You can check a working example here.

Note: This will work if both pages reside on the same domain.

So if the pages are not on the same domain, this will not work?

@Chief17 - that's right, it would violate the same domain policy for Javascript.

you can circumvent the same origin policy by having doubling up on iframes. Your main page embeds an iframe to a shim page on your own server. The shim page in turn just embeds an iframe of the foreign page. The master page can scroll the shim page since they're in the same origin. Ugly, but it works.

If you know the dimensions of the content you want to show in the iframe beforehand, you can put the iframe in a containing div, set overflow: hidden on it, and then relatively position the iframe inside that. Similar effect, no javascript.

checked your fiddle, and it doesn't seem to work. the scrollbars of the iframe didn't move :( screencast.com/t/MEvAiJA6yMCb

Scrolling an iframe with JavaScript? - Stack Overflow

javascript iframe scroll
Rectangle 27 41

The less complicated answer is to use .contents() to get at the iframe. Interestingly, though, it returns a different value from what I get using the code in my original answer, due to the padding on the body, I believe.

$('iframe').contents().height() + 'is the height'

This is how I've done it for cross-domain communication, so I'm afraid it's maybe unnecessarily complicated. First, I would put jQuery inside the iFrame's document; this will consume more memory, but it shouldn't increase load time as the script only needs to be loaded once.

Use the iFrame's jQuery to measure the height of your iframe's body as early as possible (onDOMReady) and then set the URL hash to that height. And in the parent document, add an onload event to the iFrame tag that will look at the location of the iframe and extract the value you need. Because onDOMReady will always occur before the document's load event, you can be fairly certain the value will get communicated correctly without a race condition complicating things.

var getDocumentHeight = function() {
    if (location.hash === '') { // EDIT: this should prevent the retriggering of onDOMReady
        location.hash = $('body').height(); 
        // at this point the document address will be something like help.php#1552
    }
};
$(getDocumentHeight);

...and in the parent document:

var getIFrameHeight = function() {
    var iFrame = $('iframe')[0]; // this will return the DOM element
    var strHash = iFrame.contentDocument.location.hash;
    alert(strHash); // will return something like '#1552'
};
$('iframe').bind('load', getIFrameHeight );

Hi Andrew so far very good help here. contents() works great, but I still need to test it with a bandwidth throttler. Maybe you can use the innerHeight() property. I have a problem in FF (OSX) using your solution putting the height in the hash. FF seems to keep on loading the getDocumentHeight() function in an infinitive loop? Safari is fine..

Interesting. I've added a check that prevents the setting of the hash if there's already a value there. You may need to tweak this if you are loading Help.php with a hash value (e.g. <iframe src="../Help.php#introduction" />)

By the way, Assuming you can adjust for the difference in height, you probably needn't use the hash to communicate out of the iframe. If you do use the hash method, putting a sleep(5) in your Help.php should also be a good way of testing for any race conditions. If the iframe does somehow fire onLoad before onDOMReady, it should show up here.

not work in ie11 , firefox40

jquery get height of iframe content when loaded - Stack Overflow

jquery iframe height onload
Rectangle 27 16

You can use window.postMessage to call a function between page and his iframe (cross domain or not).

<!DOCTYPE html>
<html>
<head>
    <title>iframe</title>
    <meta charset="UTF-8" />
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script>
    var Page = {
        id:'iframe',
        variable:'The iframe.'
    };

    $(window).on('message', function(e) {
        var event = e.originalEvent;
        if(window.console) {
            console.log(event);
        }
        alert(event.origin + '\n' + event.data);
    });
    $(window).on('load', function() {
        if(window.parent.postMessage) {
            window.parent.postMessage('Hello ' + Page.id, '*');
        }
    });
    </script>
</head>
<body>
    <h1>iframe</h1>
    <p>It's the iframe.</p>
</body>
</html>

jQuery/JavaScript: accessing contents of an iframe - Stack Overflow

javascript jquery iframe same-origin-policy
Rectangle 27 16

You can use window.postMessage to call a function between page and his iframe (cross domain or not).

<!DOCTYPE html>
<html>
<head>
    <title>iframe</title>
    <meta charset="UTF-8" />
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script>
    var Page = {
        id:'iframe',
        variable:'The iframe.'
    };

    $(window).on('message', function(e) {
        var event = e.originalEvent;
        if(window.console) {
            console.log(event);
        }
        alert(event.origin + '\n' + event.data);
    });
    $(window).on('load', function() {
        if(window.parent.postMessage) {
            window.parent.postMessage('Hello ' + Page.id, '*');
        }
    });
    </script>
</head>
<body>
    <h1>iframe</h1>
    <p>It's the iframe.</p>
</body>
</html>

jQuery/JavaScript: accessing contents of an iframe - Stack Overflow

javascript jquery iframe same-origin-policy
Rectangle 27 16

You can use window.postMessage to call a function between page and his iframe (cross domain or not).

<!DOCTYPE html>
<html>
<head>
    <title>iframe</title>
    <meta charset="UTF-8" />
    <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
    <script>
    var Page = {
        id:'iframe',
        variable:'The iframe.'
    };

    $(window).on('message', function(e) {
        var event = e.originalEvent;
        if(window.console) {
            console.log(event);
        }
        alert(event.origin + '\n' + event.data);
    });
    $(window).on('load', function() {
        if(window.parent.postMessage) {
            window.parent.postMessage('Hello ' + Page.id, '*');
        }
    });
    </script>
</head>
<body>
    <h1>iframe</h1>
    <p>It's the iframe.</p>
</body>
</html>

jQuery/JavaScript: accessing contents of an iframe - Stack Overflow

javascript jquery iframe same-origin-policy
Rectangle 27 2

The iframe always keeps the parent page, you should use this to detect in which page you are in the iframe:

<iframe id="iframe" frameborder="0" scrolling="no" onload="resizeIframe(this)" width="100%" src="www.google.com"></iframe>
function resizeIframe(obj) {
        alert(obj.contentWindow.location.pathname);
    }

javascript - iFrame src change event detection? - Stack Overflow

javascript jquery iframe onload
Rectangle 27 53

It's ideal if you can get the iframe to tell you itself from a script inside the frame. For example it could call a parent function directly to tell it it's ready. Care is always required with cross-frame code execution as things can happen in an order you don't expect. Another alternative is to set var isready= true; in its own scope, and have the parent script sniff for contentWindow.isready (and add the onload handler if not).

If for some reason it's not practical to have the iframe document co-operate, you've got the traditional load-race problem, namely that even if the elements are right next to each other:

<img id="x" ... />
<script type="text/javascript">
    document.getElementById('x').onload= function() {
        ...
    };
</script>

there is no guarantee that the item won't already have loaded by the time the script executes.

The ways out of load-races are:

Inline onsomething handlers in HTML are almost always the wrong thing and to be avoided, but in this case sometimes it's the least bad option.

Thanks. My solution checks the readyState (if exists), then the body elements innerHTML length to see if it has loaded. If not, attaches the load event handler. Seems to work ok

-1 - inline events are not "bad", that's just the current fad. In fact, inline events are easier to debug and understand, unlike their magic counterparts (which, on the other hand, are easier to attach, stack and use seamlessly).

@Christian, inline events are also the best option when you need to attach an event to every element of a very long list. Since you're already looping to build the list on the server side, it's much more efficient to attach the inline-event as well.

@haknick Wouldn't you want to use a single event listener on the list, and use an event delegate? This would be more efficient.

This would not work if the iframe is cross-domain. The script inside iframe cannot access parent window.

javascript - Detecting when Iframe content has loaded (Cross browser) ...

javascript events cross-browser
Rectangle 27 1

The iframe always keeps the parent page, you should use this to detect in which page you are in the iframe:

<iframe id="iframe" frameborder="0" scrolling="no" onload="resizeIframe(this)" width="100%" src="www.google.com"></iframe>
function resizeIframe(obj) {
        alert(obj.contentWindow.location.pathname);
    }

javascript - iFrame src change event detection? - Stack Overflow

javascript jquery iframe onload
Rectangle 27 3

You've got a server that will return to you information -- you could place this information in an IFRAME... or you can call a JavaScript function to retrieve that information and display it in a location (DIV) you set aside on your page.

Here is a sample HTML page that will retrieve information from the server using AJAX

<html>
<head>
<script type="text/javascript">
function getAreaInfo(id)
{
  var infoBox = document.getElementById("infoBox");
  if (infoBox == null) return true;
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState != 4) return;
    if (xhr.status != 200) alert(xhr.status);
    infoBox.innerHTML = xhr.responseText;
  };
  xhr.open("GET", "info.php?id=" + id, true);
  xhr.send(null);
  return false;
}
</script>
<style type="text/css">
#infoBox {
  border:1px solid #777;
  height: 400px;
  width: 400px;
}
</style>
</head>
<body onload="">
<p>AJAX Test</p>
<p>Click a link...
<a href="info.php?id=1" onclick="return getAreaInfo(1);">Area One</a>
<a href="info.php?id=2" onclick="return getAreaInfo(2);">Area Two</a>
<a href="info.php?id=3" onclick="return getAreaInfo(3);">Area Three</a>
</p>
<p>Here is where the information will go.</p>
<div id="infoBox">&nbsp;</div>
</body>
</html>

And here is the info.php that returns the information back to the HTML page:

<?php
$id = $_GET["id"];
echo "You asked for information about area #{$id}. A real application would look something up in a database and format that information using XML or JSON.";
?>

+1 for using pure JavaScript.

How exactly can I replace an iframe with a div and Javascript? - Stack...

javascript iframe html
Rectangle 27 3

You've got a server that will return to you information -- you could place this information in an IFRAME... or you can call a JavaScript function to retrieve that information and display it in a location (DIV) you set aside on your page.

Here is a sample HTML page that will retrieve information from the server using AJAX

<html>
<head>
<script type="text/javascript">
function getAreaInfo(id)
{
  var infoBox = document.getElementById("infoBox");
  if (infoBox == null) return true;
  var xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState != 4) return;
    if (xhr.status != 200) alert(xhr.status);
    infoBox.innerHTML = xhr.responseText;
  };
  xhr.open("GET", "info.php?id=" + id, true);
  xhr.send(null);
  return false;
}
</script>
<style type="text/css">
#infoBox {
  border:1px solid #777;
  height: 400px;
  width: 400px;
}
</style>
</head>
<body onload="">
<p>AJAX Test</p>
<p>Click a link...
<a href="info.php?id=1" onclick="return getAreaInfo(1);">Area One</a>
<a href="info.php?id=2" onclick="return getAreaInfo(2);">Area Two</a>
<a href="info.php?id=3" onclick="return getAreaInfo(3);">Area Three</a>
</p>
<p>Here is where the information will go.</p>
<div id="infoBox">&nbsp;</div>
</body>
</html>

And here is the info.php that returns the information back to the HTML page:

<?php
$id = $_GET["id"];
echo "You asked for information about area #{$id}. A real application would look something up in a database and format that information using XML or JSON.";
?>

+1 for using pure JavaScript.

How exactly can I replace an iframe with a div and Javascript? - Stack...

javascript iframe html
Rectangle 27 1

You can do this by adding an event handler for when the iframe loads. In this function, get the src of the iframe, and apply different styles based on it using a switch statement:

<iframe id="myFrame"></iframe>
document.getElementById('myFrame').onload= function() {
  switch( this.src ){
     case 'http://example.com/index' : // Will fall through and execute same code as below
     case 'http://example.com/'      : this.style.width  = '400px';
                                       this.style.height = '200px';
                                       break; // Stop switch
     case 'http://example.com/about' : this.style.width  = '700px';
                                       this.style.height = '500px';
                                       break;
     default : /* Do something or not */
  }
};

javascript - How can i dynamically change the size of an iframe when u...

javascript php html iframe
Rectangle 27 23

You need to attach an event to an iframe's onload handler, and execute the js in there, so that you make sure the iframe has finished loading before accessing it.

$().ready(function () {
    $("#iframeID").ready(function () { //The function below executes once the iframe has finished loading
        $('some selector', frames['nameOfMyIframe'].document).doStuff();
    });
};

The above will solve the 'not-yet-loaded' problem, but as regards the permissions, if you are loading a page in the iframe that is from a different domain, you won't be able to access it due to security restrictions.

this is a good idea, in fact I was trying it just as you answered. However, it doesn't work around the permission denied (it does address my having to wait before starting to access the iframe stuff)

actually... nevermind, it seems that the wait is still required even when doing this.

A couple of notes on this code: you should use iframe.contentDocument instead of .document, and you should use .load() instead of .ready() to avoid the wait. (Not perfect, but better)

@RodrigoQueiro Which usage of ready should be load? Both?

jQuery/JavaScript: accessing contents of an iframe - Stack Overflow

javascript jquery iframe same-origin-policy
Rectangle 27 23

You need to attach an event to an iframe's onload handler, and execute the js in there, so that you make sure the iframe has finished loading before accessing it.

$().ready(function () {
    $("#iframeID").ready(function () { //The function below executes once the iframe has finished loading
        $('some selector', frames['nameOfMyIframe'].document).doStuff();
    });
};

The above will solve the 'not-yet-loaded' problem, but as regards the permissions, if you are loading a page in the iframe that is from a different domain, you won't be able to access it due to security restrictions.

this is a good idea, in fact I was trying it just as you answered. However, it doesn't work around the permission denied (it does address my having to wait before starting to access the iframe stuff)

actually... nevermind, it seems that the wait is still required even when doing this.

A couple of notes on this code: you should use iframe.contentDocument instead of .document, and you should use .load() instead of .ready() to avoid the wait. (Not perfect, but better)

@RodrigoQueiro Which usage of ready should be load? Both?

jQuery/JavaScript: accessing contents of an iframe - Stack Overflow

javascript jquery iframe same-origin-policy
Rectangle 27 23

You need to attach an event to an iframe's onload handler, and execute the js in there, so that you make sure the iframe has finished loading before accessing it.

$().ready(function () {
    $("#iframeID").ready(function () { //The function below executes once the iframe has finished loading
        $('some selector', frames['nameOfMyIframe'].document).doStuff();
    });
};

The above will solve the 'not-yet-loaded' problem, but as regards the permissions, if you are loading a page in the iframe that is from a different domain, you won't be able to access it due to security restrictions.

this is a good idea, in fact I was trying it just as you answered. However, it doesn't work around the permission denied (it does address my having to wait before starting to access the iframe stuff)

actually... nevermind, it seems that the wait is still required even when doing this.

A couple of notes on this code: you should use iframe.contentDocument instead of .document, and you should use .load() instead of .ready() to avoid the wait. (Not perfect, but better)

@RodrigoQueiro Which usage of ready should be load? Both?

jQuery/JavaScript: accessing contents of an iframe - Stack Overflow

javascript jquery iframe same-origin-policy
Rectangle 27 2

You can use jQuery's load function that fires onload or reload.

You will need to store the number of times the iframe has reloaded.

var reloaded = 0;
$("#iframe_id").load(function(){
    reloaded++;
});

Really? This is simply a content loaded event, regardless of the origin.

seems redirect response does not trigger the load event, only the final response triggered.

javascript - How can I detect if an iFrame gets redirected to another ...

javascript redirect iframe
Rectangle 27 1

I have encountered the same problem as this: Here is my work-around, please see if it works for you:

<script>
 function download(){
    var url = 'http://example.com/dload.py';
    var htm = '<iframe src="' + url +'" onload="downloadComplete()"></iframe>';
    document.getElementById('frameDiv').innerHTML = htm;
 }
</script>

<div style="display:none" id="frameDiv">
</div>
<button onclick="download()">download file</button>

As far as I can remembered iframe's onload event fires only once. Setting another value for src attribute will not cause the onload event to fire again.

Very clever! Thank you. It doesn't work in Chrome, but at least in Firefox it works, and works multiple times, since every time it's actually a new iframe that fires the onload event, since you overwrite innerHTML.

This appeared to work for a similar issue that I had - as long as Firebug was running. When I tried in Firefox 2 or 3 without Firebug, all of a sudden the onload wouldn't fire. Anyone know where the difference is?

How to trigger onload event when downloading a file in an iframe? - St...

iframe onload download
Rectangle 27 1

My solution after many different approaches to get this working across ff ie safari and chrome was not have a 2 step download.

the original JS request to create an iframe loads a src that would normally have loaded the pdf However, the src now loads a page with yet another iframe inside of it, which now contains the url of the pdf. in the html response I trigger the onload and also a catchall setTimeout funciton which calls my response on window.parent.window.handlerfunction which my onload on the top iframe would have been. The result is a PDF download and a trigger on the top level parent of the handler function that works across the browsers since it no longer relies on detecting an actual iframe load but rather relies on supported parent/child window relationships.

hope this helps someone who was also stuck

How to trigger onload event when downloading a file in an iframe? - St...

iframe onload download
Rectangle 27 4

If you want the iframe and its contents to scale when the window resizes, you can set the following to the window's resize event as well as the iframes onload event.

function()
{
    var _wrapWidth=$('#wrap').width();
    var _frameWidth=$($('#frame')[0].contentDocument).width();

    if(!this.contentLoaded)
      this.initialWidth=_frameWidth;
    this.contentLoaded=true;
    var frame=$('#frame')[0];

    var percent=_wrapWidth/this.initialWidth;

    frame.style.width=100.0/percent+"%";
    frame.style.height=100.0/percent+"%";

    frame.style.zoom=percent;
    frame.style.webkitTransform='scale('+percent+')';
    frame.style.webkitTransformOrigin='top left';
    frame.style.MozTransform='scale('+percent+')';
    frame.style.MozTransformOrigin='top left';
    frame.style.oTransform='scale('+percent+')';
    frame.style.oTransformOrigin='top left';
  };

This will make the iframe and its content scale to 100% width of the wrap div (or whatever percent you want). As an added bonus, you don't have to set the css of the frame to hard coded values since they'll all be set dynamically, you'll just need to worry about how you want the wrap div to display.

I've tested this and it works on chrome, IE11, and firefox.

html - How can I scale the content of an iframe? - Stack Overflow

html css dom
Rectangle 27 1

I faced similar problem. I solved it without using onload handler.I was working on AngularJs project so i used $interval and $ timeout. U can also use setTimeout and setInterval.Here's the code:

var stopPolling;
 var doIframePolling;
 $scope.showIframe = true;
 doIframePolling = $interval(function () {
    if(document.getElementById('UrlIframe') && document.getElementById('UrlIframe').contentDocument.head && document.getElementById('UrlIframe').contentDocument.head.innerHTML != ''){
        $interval.cancel(doIframePolling);
        doIframePolling = undefined;
        $timeout.cancel(stopPolling);
        stopPolling = undefined;
        $scope.showIframe = true;
    }
},400);

stopPolling = $timeout(function () {
        $interval.cancel(doIframePolling);
        doIframePolling = undefined;
        $timeout.cancel(stopPolling);
        stopPolling = undefined;
        $scope.showIframe = false;     
},5000);

 $scope.$on("$destroy",function() {
        $timeout.cancel(stopPolling);
        $interval.cancel(doIframePolling);
 });

Every 0.4 Seconds keep checking the head of iFrame Document. I somthing is present.Loading was not stopped by CORS as CORS error shows blank page. If nothing is present after 5 seconds there was some error (Cors policy) etc.. Show suitable message.Thanks. I hope it solves your problem.

Uncaught DOMException: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "..." from accessing a cross-origin frame.

jquery - Catch error if iframe src fails to load . Error :-"Refused to...

jquery iframe knockout.js same-origin-policy