Search code examples
javascripturliframemozilla

iFrame URL in Mozilla


I need help with getting URL of iFrame element in mozilla. While this code works perfectly in IE it does not work in mozilla.

<iframe id="frame" onload="myFunction()" src="./upload/" ></iframe>

<script type="text/javascript" >
   function myFunction()
   {                            
      var a = document.getElementById("frame").contentWindow.location.href;
      alert(a)
   }
</script>

Can you please tell me how to make it work in mozilla ? I don`t need the src of the iframe but changing URL according to iframe location. Webpage and iframe content are both on the same domain.

I found out that these two codes works perfectly only in IE:

document.getElementById("frame").contentWindow.location.href;
document.frames['frame'].location.pathname;

Also location.pathname and location.href without iframe work also in chrome and mozilla. But if i add document.getElementById("frame") or document.frames['frame'] it stops working in chrome and mozilla.


Solution

  • Your code, I tested this in FireFox 52.0.1 and IE 11.

    <iframe id="frame" onload="myFunction()" src="http://stackoverflow.com/questions/42905168/iframe-url-in-mozilla/42905409" ></iframe>
    <script type="text/javascript">
    window.addEventListener("load", function(){
        document.getElementById('frame').onload = myFunction;
    });
    function myFunction() {
        var a = document.getElementById("frame").src;
        var parser = document.createElement('a');
        parser.href = a;
        parser.protocol; // => "http:"
        parser.hostname; // => "stackoverflow.com"
        parser.port;     // => "80"
        parser.pathname; // => "/questions/42905168/iframe-url-in-mozilla/42905409"
        parser.search;   // => ""
        parser.hash;     // => ""
        parser.host;     // => "stackoverflow:80"
        alert(a);
    } 
    </script>
    

    There was a funny issue with IE not figuring out the onload event through Javascript.

    To Get the src

    window.addEventListener("load", function(){ alert(document.getElementById("frameid").src); });

    The window.addEventListener is added to make sure the DOM is loaded completely.

    To set the src document.getElementById('frameid').setAttribute("src",someurlhere);