仅跟踪iframe历史记录

时间:2012-05-24 21:30:16

标签: javascript html html5 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历史记录?

6 个答案:

答案 0 :(得分:4)

有一种简单的方法可以做到这一点,前提是iframe内容是同一个域。

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

答案 1 :(得分:4)

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

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

编辑:您必须维护您的navigationhistory服务器端。如同另一个答案中所述,在主窗口上保持一个数组,当您也使用父窗口导航时,它不起作用。

答案 2 :(得分:3)

使用它来访问iframe的历史记录

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

答案 3 :(得分:1)

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

您是否尝试过在页面本身和iframe上设置域名相同? e.g。

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

这应该向浏览器发出信号,表明页面彼此信任并且应该被授予访问其内部状态的权限

答案 4 :(得分:0)

如果框架包含 contentWindow ,您可以使用 frame.contentWindow.history

但并非所有浏览器都支持此属性。如果不是,则帧的位置应存储在某些变量中。 在你的frame 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);

答案 5 :(得分:0)

只要您有权访问这两个域,

ITS可能就可以击败SOP。您可以使用帮助程序IFRAME从BODY传递更改事件。

这篇文章应该非常有用: Resizing an iframe based on content

相关问题