2012-05-24 217 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