Karandeep Singh
Karandeep Singh

Reputation: 1279

iframe location in javascript

In this example, alert is blank; I want to read the location of iFrame, I am using object.src for this but it work only if I set its src attribute. But I set iFrame's location using window.open method and in this case it is not working. What I do ?

<body>    
<iframe id="location" name="address" style="width:700px; height:700px;">  
</iframe>    
<script type="text/javascript" language="javascript">  
    window.open("http://www.google.com","address");  
    function clickMe()  
    {  
        var src = document.getElementBy Id("location").src;  
        alert(src);  
    }  
</script>  
<input type="button" onclick="clickMe()" value="click Me"/>  
</body>

Upvotes: 2

Views: 20097

Answers (2)

quantumSoup
quantumSoup

Reputation: 28162

Instead of using window.open(), why don't you just use:

document.getElementById("location").src = "http://www.google.com";

Now you can get its location using getElementById()

You can do that by accessing the location.href attribute. Of course, for security reasons, browsers won't let you access the iframe's DOM if it's another domain.

var oIframe = document.getElementById("location");
// for compatibility
var oDoc = oIframe.contentWindow || oIframe.contentDocument;
if (oDoc.document) {
    oDoc = oDoc.document;
}
alert(oDoc.location.href);

Upvotes: 4

mplungjan
mplungjan

Reputation: 178285

Same security issue if you access via the handle which should work in the same domain

<script>
var win;
function load(link) {
  win=window.open(link.href,link.target)
  return win?false:true;
}
function tell(winName) {  
  try {
    alert(win.location.href)
    try {
      var handle = window.open('',winName);
      alert(handle.location.href)
    }
    catch(e) {
      alert('oops getting location via window handle:'+e.message)
    }
  }
  catch(e) {
    alert('Ooops getting location:'+e.message)
  }
}  
</script>

<iframe src="about:blank" name="if1"></iframe><br/>
<a href="http://www.google.com" target="if1" onClick="return load(this)">Load foreign link</a><br />
<a href="showhref.html" target="if1" onClick="return load(this)">Load local link</a><br />
<a href="#" onClick="return tell('if1')">Tell</a><br />

Upvotes: 2

Related Questions