9

this is the code im using.............

i want to get current url(href) from below code ...............

<html>
<head>
<script type="text/javascript">
        function load() {
            var url =  document.getElementById("iframeid");  

          //get the ifram onload url of href 
    //(i.e)   http://www.image.com/home.html     

        }
    </script>
</head>
<body>
<iframe onload="load()" name="Google"  id="iframeid"  scrolling="auto" style="width:95%;height:600px" src="http://www.image.com" >

    </iframe>
</body>
</html>

5 Answers5

23

This will work only if they are in the same domain,protocol and port:

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

else use :

document.getElementById("iframe_id").src
qlayer
  • 344
  • 3
  • 7
  • 2
    i have undefined result with this code –  Aug 22 '12 at 09:41
  • 10
    `document.getElementById("iframe_id").src` will always return the initial uri.. so not recommended to use it. – Amit Shah Oct 12 '16 at 05:10
  • Note: [Changing origin](https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy#Changing_origin) is possible, but only for subdomain access. – Mark G Nov 11 '18 at 00:45
5

The demo.

<html>
<head>
<script type="text/javascript">
        function load(frame) {
            console.log(frame.src);
        }
</script>
</head>
<body>
<iframe onload="load(this)" name="Google"  id="iframeid"  scrolling="auto" style="width:95%;height:600px" src="http://www.image.com" >
</iframe>
</body>
</html>
xdazz
  • 158,678
  • 38
  • 247
  • 274
2

Try this:

document.getElementById("iframeid").src;

sQVe
  • 1,977
  • 12
  • 16
1

Only two missing bits (marked with <== )

<html>
<head>
<script type="text/javascript">
        function load() {
            var url =  document.getElementById("iframeid").src; // <== .src

            //get the ifram onload url of href 
            //(i.e)   http://www.image.com/home.html     

        }
    </script>
</head>
<body>
<iframe onload="load()" name="Google"  id="iframeid"  scrolling="auto" style="width:95%;height:600px" src="http://www.image.com" > // <== Opening angle bracket

    </iframe>
</body>
</html>
Lucas Green
  • 3,951
  • 22
  • 27
1

try this. Sometimes you can't acess the Iframe url

var CurrentUrl = document.getElementById('MyIFrame').contentWindow. location.href;
Parag Tyagi
  • 8,780
  • 3
  • 42
  • 47
Coder
  • 886
  • 1
  • 12
  • 28