总是在fancyBox iframe中打开html页面

Always open a html page in fancyBox iframe

本文关键字:html 页面 iframe fancyBox      更新时间:2023-09-26

我使用Fancybox在Fancybox中显示外部html页面,例如:在page1中,我设置了一个链接,该链接以Fancybox iframe模式打开page2,并且工作良好。

问题是:

是否有可能,如果有人试图进入page2的URL,使page2始终从page1而不是像正常页面一样的浏览器窗口在fancybox中打开?

是的,有可能。

所以第一页(parent.html),将打开第二页(iframed.html)在fancybox从一个链接,如

<a id="openIframe" class="fancybox" href="iframed.html">Open page inside fancybox iframe</a>

注意,我设置了一个ID和一个链接,将打开框架页面。

然后是每页的脚本:

parent.html

父页应该有两个特定的代码:

  • 初始化fancybox的代码
  • 一个代码来检测hash是否存在于URL中,以便它可以触发fancybox

:

// initialize fancybox
$(".fancybox").fancybox({
    // API options
    type: "iframe" //<== at least this one
});
if (window.location.hash) {
    // detect if URL has hash and trigger fancybox
    $(window.location.hash + ".fancybox").trigger("click");
    // remove hash after fancybox was opened 
    // two methods to cover most browsers
    if (navigator.userAgent.match(/msie/i)) {
        var loc = window.location.href;
        index = loc.indexOf('#');
        if (index > 0) {
            window.location = loc.substring(0, index);
        }
    } else {
        history.pushState("", document.title, window.location.pathname);
    };
};

然后第二页(iframed.html)应该有一个代码来检测是否本身已经在iframe中打开了(在我们的情况下是fancybox iframe)。

如果没有,它应该重定向到父页面,目标是打开fancybox的链接的ID,所以:

iframed.html

if (self == top) {
    window.location.href = "parent.html#openIframe";
};

注意 self == top将返回true,如果页面不是在iframe内打开的,所以它重定向到父页面。

请参阅JSFIDDLE(并尝试在新窗口/选项卡中打开链接)