2012-05-24 129 views
4

我有一个包含iframe的页面,我只想跟踪iframe的历史记录。 我试图用这样的历史对象:只跟踪iframe历史

<!DOCTYPE html> 
<html> 
    <head> 
     <title></title> 
     <script type="text/javascript"> 
     function checkFrameHistory() { 
      alert(window.frames["test2"].history.length); 
     } 

     function checkThisHistory() { 
      alert(history.length); 
     } 
     </script> 
    </head> 
    <body> 

     <iframe name="test2" src="test2.html"></iframe> 

     <div> 
      <input type="button" onclick="checkFrameHistory()" value="Frame history"/> 
      <input type="button" onclick="checkThisHistory()" value="This history"/> 
     </div> 

    </body> 
</html> 

test2.html

<!DOCTYPE html> 
<html> 
    <head> 
     <title></title> 
     <script type="text/javascript"> 
     function checkMyHistory() { 
      alert(history.length); 
     } 
     </script> 
    </head> 
    <body> 
    <div> 
     Test2 
    </div> 

    <div> 
     <input type="button" onclick="checkMyHistory()" value="My history"/> 
    </div> 

    </body> 
</html> 

但它实际上给我的历史,包括父窗口。

例如,我去了主窗口中的另一个站点,并返回到我的iframe测试站点。 window.frames["test2"].history.lengthhistory.length仍然给我通过增加长度相同的计数2.

我做错了吗?有没有办法只跟踪iframe的历史?

+0

中有什么test2.html页? – thisgeek

+0

刚刚添加了test2.html,但它只是一个简单的测试页面。谢谢! – evanwong

+0

此[INFO](http://khaidoan.wikidot.com/iframe-and-browser-history)可以提供更多信息。 – arttronics

回答

1

由于same-origin policy,您不可能访问任何与该帧关联的对象。

您是否尝试过在页面本身和iframe上设置域相等?例如

//somewhere on your page in a script tag 
document.domain = "your-top-level-domain.com"; 

这应该发出信号,告知页面相互信任,并应给予其内部状态的访问浏览器

+0

嗯......目前这些html页面是本地主机,应该已经在同一个域名中了......看起来像我可以像iframe一样访问历史记录:'window.frames [“test2”]。history' .. 。至少我没有得到任何错误...它只是框架的历史对象似乎包括原始页面的历史,而不是仅指iframe的历史... – evanwong

+0

哦,我看到我的错误。对,试着改变你的代码来访问iframe,例如'window.frames [“test2”]。contentWindow.history'。 'contentWindow'是重要的部分 – WickyNilliams

4

有一个简单的方法来做到这一点,当然前提是iframe中的内容是相同的域。

从父项绑定到iframe的窗口对象的beforeUnloadload事件。在事件的回调处理程序中,您只需沿着locations.push(getElementById("iframe").contentWindow.location.href)的行执行某些操作,其中位置当然是父范围中先前定义的数组。

+0

我可以使用相同的不同的域名网址吗?如果没有,为什么它不可能? –

4

Chrome在窗口基础上管理历史;不在单独的框架上。此行为可能是您的问题的原因。

不知道它的所有浏览器btw的默认行为。

编辑:你必须维护你的navigationhistory服务器端。正如另一个答案中所述,在主窗口上保存一个数组,当您还使用父窗口进行导航时,该窗口不起作用。

+0

解释问题根源的有效点,但缺乏解释如何解决问题的解释。 –

3

使用这种访​​问IFRAME

document.getElementById("test2").contentWindow.history.length 
+0

这不适用于跨网站 –

0

如果帧包含contentWindow的历史,你可以使用frame.contentWindow.history

但并非所有浏览器都支持此属性。如果没有,框架的位置应该存储在一些变量中。在你的框架onload事件 绑定事件处理程序如下图所示(使用jquery)

var frameHistory = []; 
$(document).ready(function(){ 
    var frame = window.frames["test2"]; 
    $.bind(frame, "onload", function(){ //store location when frame loads 
     frameHistory.push(frame.window.location.href); 
    } 
}); 

而在你的按钮单击事件处理程序:

alert(frameHistory.length); 
0

及其可能击败SOP只要你有机会到两个域。您可以使用助手IFRAME从BODY传递change事件。

这个职位应该是非常有帮助的: Resizing an iframe based on content