开发者

iframe location in javascript

In this example, alert is blank; I want to 开发者_StackOverflow中文版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>


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);


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜