讓我們假設您有兩個框架A和B(或帶有iframe的頁面)。 A有一個功能foo()
,它在完成時調用回調。 B中的腳本從A調用foo()
,但在它完成(並調用B的回調)之前,B的src被完全替換,以便回調不再具有執行上下文。在大多數瀏覽器中,這會產生某種錯誤。當調用幀(和執行上下文)消失時處理回調
有沒有什麼辦法可以檢測回調來自不再有執行上下文的運行時,因此不應該被調用?
這裏是包裝頁面:
<html>
<head>
<script>
var load = function() {
document.getElementById("link").onclick = function(){
document.getElementById("iframe").src = "test-exec-context-frame-src.html";
return(false);
};
};
var frameLoad = function(cb) {
// kill the frame and then callback
document.getElementById("iframe").src = "http://www.google.com";
cb();
};
</script>
</head>
<body onload="load();">
<div>This is the first div, click <a id="link" href="#">here</a> to start</div>
<iframe id="iframe"></iframe>
</body>
這裏是IFRAME SRC頁:
<html>
<head>
<script>
var load2 = function() {
document.getElementById("link").onclick = function(){
top.frameLoad(function(){
console.log("I am done");
});
};
};
</script>
</head>
<body onload="load2();">
<div>This is the internal frame. Click <a href="#" id="link">here</a> to force the callback.</div>
</body>
在第一頁中點擊鏈接時, iframe加載第二個源頁面。點擊第二頁的鏈接,它會用回調函數調用top.frameLoad。在回調運行之前,iframe src被更改爲www.google.com,銷燬回調的執行上下文。回調運行並創建一個錯誤。
在嘗試執行回調之前,我們如何檢查回調的執行上下文(或者調用函數)?
(忽略格式,使用全局變量的,但事實上,jQuery的將處理它比的document.getElementById等更好這僅僅是一個測試。)
我有一個嘗試/抓住正在接受測試,不知道如果它可以跨瀏覽器(任何人都說「IE」?)。目的是肯定**不**以改變iframe src,這發生在外部。這只是模擬實際發生的事情。 – deitch 2011-05-04 09:04:03
即使try/catch工作,我仍然想知道是否有任何方法可以正確處理這個問題(除了完全殺死幀,當然這是正確的解決方案)。 – deitch 2011-05-04 12:20:53
僅供參考,try/catch不起作用,因爲try/catch本身在框架內。 – deitch 2011-05-30 22:54:43