Ask your JavaScript questions! Pay money and get answers fast! (more info)

get the current url of my iframe and inject this in my URL JavaScript

the URL of my page is http://mysite.com

In this page i have just an iframe.

In this iframe, there is this site : http://yoursite.com

when i click on a link in the iframe i change the content of my iframe.
For example, the content of my iframe become : http://yoursite.com/page1

In this case i want that the url of my page become http://mysite.com/#page1

Answers (2)

2013-02-25

Daniel Mesteru answers:

Hi,

Try this:

document.getElementById('mainContent').contentWindow.location.href
or
var CurrentUrl = document.getElementById('MyIFrame').contentWindow. location.href;


You can try this code:

<html>
<head>
<script type="text/javascript">
<!--
function setSrc(obj, url) {
obj.src = url;
}

function getSrc(obj) {
alert(obj.src);
return obj.src;
}
//-->
// above is the code to get the url from your frame

// now we place that url into the input box:
document.getElementById("frameid").value = myframe; // with frameURL defined earlier
</script>
</head>
<body>
<p>|
<a href="#" onclick="javascript:getSrc(document.getElementById('myframe '))">Get src</a> - displays with alert</p>

<iframe id="myframe" src="http://www.google.com"></iframe>
<br>
<br>
<input Id="frameid"><p>frameurl not showing in input</p>
</body>
</html>


sebastien comments:

that's your code : http://demo2.archiparmentier.com
What must i do ?


sebastien comments:

i see no site in the iframe


sebastien comments:

it's ok now, i see the content of the iframe, but where is displayed the url of the current content of the iframe ?


sebastien comments:

Hi... could you help me ? :-)

2013-02-25

mohitseth answers:

My solution is using jQuery. You have to do following:

$("#iframeID").contents().find('a').each(function () {
var href = $(this).attr('href').split("/"),
newHref = href[href.length-1];
$(this).attr("href", "http://mysite.com/#" + newHref).
attr("target", "_top");
});

I don't know why I am not able to reply to your comments. So yes this solution is not working because it doesn't comply to same origin policy. The iframe has to be from the same domain only otherwise it will throw out errors.


sebastien comments:

this is your code : http://demo2.archiparmentier.com/index2.html
that seems not work...


sebastien comments:

Hi... could you help me ? :-)