views:

37

answers:

2

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>
+1  A: 

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);
quantumSoup
I know about it, In question I also write if I set its src attribute then its works, But I want to know the way how to read the location when we use open method ?
Karandeep Singh
I see. Refer to edit.
quantumSoup
+1  A: 

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 />
mplungjan