5

我有一个包含 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.length通过history.length将长度增加 2 给了我相同的计数。

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

4

6 回答 6

5

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

不知道它是否适用于所有浏览器的默认行为。

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

于 2012-06-04T16:31:07.557 回答
4

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

从您绑定到iframe 窗口对象的beforeUnload或事件的父级。load在事件的回调处理程序中,您只需按照locations.push(getElementById("iframe").contentWindow.location.href)where 位置当然是父范围中先前定义的数组来做一些事情。

于 2012-06-04T12:43:30.070 回答
3

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

document.getElementById("test2").contentWindow.history.length
于 2012-06-04T18:33:31.310 回答
1

由于同源策略,您不太可能访问与框架关联的任何对象。

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

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

这应该向浏览器发出信号,表明页面相互信任,并且应该可以访问它们的内部状态

于 2012-05-29T15:16:50.533 回答
0

If the frame contains contentWindow, you can use frame.contentWindow.history.

But not all browsers support this property. If not, the frame's location should be stored in some variables. Bind event handler on your frame onload event like below(using 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);
    }
});

And in your button click event handler:

alert(frameHistory.length);
于 2012-06-05T06:14:43.390 回答
0

只要您可以访问这两个域,就有可能击败 SOP。您可以使用辅助 IFRAME 从 BODY 传递 onchange 事件。

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

于 2012-06-05T13:36:29.597 回答