Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect current iframe url?

I wrote a html code which initializes my iframe with another site.

my domain is for example:

www.mydomain.com/Index.html

in this there's an

 <iframe src = "www.anotherdomain.com/pages/firstPage.html"/>

I want to detect the complete new src url whenever the iframe gets new one. The iframe text consists links to other pages within the initialised page. Is it possible and legal to get it done ? Thanks. Any help is appreciated.

I guess it goes to cross origin issues but is there a work around for this ?

Update

I tried to get the answer by

 document.getElementById("myIframeId").src

at the frame load event. But it keeps showing the src with which it is initialised. It is not showing the updated src.

document.getElementById("myIframeId").contentWindow.location.href

gives the Security Error that a http frame is trying to access https in the iframe. Protocols mismatched.

I made the localhost to SSL and used https but the request got blocked. I don't know why.

like image 283
Indish Cholleti Avatar asked Oct 03 '15 06:10

Indish Cholleti


2 Answers

I don't agree with the answers which suggest that you should use "src" to detect the current url of the iframe. It simply doesn't give you the current url - but the url it started with.

The domain has to be from the same origin to use the method of the following code:

$(document).ready(function() {
  $('#myframe').load(function() {
    alert($(this).get(0).contentWindow.location.href);
  }); 
});

If the domains are from different origins - but you have access to both (or both are yours), then you can use window.postMessage function and contentWindow property of iFrame to send the data for the parent to show when a new page loads.

Here is a tutorial on that: http://javascript.info/tutorial/cross-window-messaging-with-postmessage

And if the domain in the iFrame is completely alien, one approach I can think of is to load that domain in a server side script and get it to render this data with altered links. Now you can call this script inside the iFrame and use contentWindow.location.href property whenever it loads.

like image 69
Charlie Avatar answered Nov 12 '22 14:11

Charlie


You can check the src property on an interval to see if it's changed. Here's a function that will do that for you.

function watchIframeSRC(iframe, callback, interval) {
    // check every 1 second by default
    if (typeof interval === 'undefined') {
        interval = 1000;
    }
    var src = iframe.src;
    return setInterval(function () {
        // invoke the callback if the src is different
        if (iframe.src !== src) {
            src = iframe.src;
            callback(iframe);
        }
    }, interval);
}

var iframe = document.getElementById('test');

watchIframeSRC(iframe, function (iframe) {
    console.log("iframe src:", iframe.src);
});
like image 45
Ilia Choly Avatar answered Nov 12 '22 13:11

Ilia Choly