更新时间:2021-10-05 22:22:10
您遇到了相同的问题来源政策:框架页面在与父窗口不同的主机上提供.我的答案包括两种解决方案:
You're having trouble with the Same origin policy: The framed page is served at a different host than the parent window. My answer consists of two solutions:
<iframe>
, http://jsfiddle处附加和处理onload
事件. net/BYssk/1/ window.postMessage
(请参阅答案底部,推荐), http://jsfiddle.net/5fGRj/1/ onload
event at the <iframe>
, http://jsfiddle.net/BYssk/1/
window.postMessage
(see bottom of answer, recommended), http://jsfiddle.net/5fGRj/1/
要解决此问题,您可以使用以下方法之一.两种方法都要求必须关闭框架中的页面.这可以通过提交表格来实现.不需要onclick
处理程序. 两种方法的预览: http://jsfiddle.net/BYssk/1/
To deal with this, you've can use one of the following methods. Both methods requires that the page in the frame reloads when it has to be closed. This can be achieved by submitting the form. No onclick
handlers are necessary. Preview of both methods: http://jsfiddle.net/BYssk/1/
1.如果您的iFrame嵌入在页面中:
1. If your iFrame is embedded in the page:
<script>
var fancyboxClose = (function(){ //Define a function
var loaded = 0; //Define a local, "PRIVATE" counter
return function(){ //Define a public method
// Increases the counter by one, modulo 2:
// Every "first" time, the "loaded++" returns an even number -> false
// When the page reloads again, the fancybox is submitted. The counter
// increases again -> odd number => modulo 2 = 1 => true
if(loaded++ % 2) $.fancybox.close();
}
})();
</script>
<iframe src=".." onload="fancyboxClose()"></iframe>
2.如果您的iFrame是动态创建的:
2. If your iFrame is dynamically created:
//The code below is executed inside some function. Definitely NOT globally
var loaded = 0;
$("<iframe>") // Create frame
.load(function(){ // Bind onload event
if(loaded++ % 2) $.fancybox.close();
})
.attr("src", "...") // Set src attribute
.appendTo("body"); // Append the iframe, anywhere. For example: <body>
此方法背后的引擎:
onload
事件(1).onload
事件(2).onload
事件中不执行任何操作.但是,在第二个onload
事件中,脚本将调用$.fancybox.close()
方法.onload
event is triggered (1).onload
event is triggered (2).onload
event. At the second onload
event however, the script calls the $.fancybox.close()
method.
另一种方法包括使用现代的 window.postMessage
方法.它比以前的方法可靠得多,并且在所有现代浏览器中均受支持. 提琴: http://jsfiddle.net/5fGRj/1/
Another method consists of using the modern window.postMessage
method. It's much more reliable than the previous method, and supported in all modern browsers. Fiddle: http://jsfiddle.net/5fGRj/1/
主窗口中的脚本:
function closeFancyBox(){
$.fancybox.close();
}
window.addEventListener("message", closeFancyBox, false);
框架页面内的必要代码:
Necessary code inside the framed page:
<script>
function initiateClose(){
parent.postMessage("Close fancybox please.", "*");
// * should be more specific, for security reasons
// See https://developer.mozilla.org/en/DOM/window.postMessage
}
</script>
PostMessage method<br />
<input type="submit" value="Inititate 'close'" onclick="initiateClose()">