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.
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.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With