如何检查iframe是否被自己加载

How to check if iframe is loaded by itself?

本文关键字:是否 自己 加载 iframe 何检查 检查      更新时间:2023-09-26

我有一个iframe来加载用户请求的内容。但是,我需要确保iframe不加载自己,而是重定向到默认站点。

这个过程必须是动态的,并且可以在任何页面上工作,因为我有多个页面这样做,并且每个站点的自定义代码将不实用。

只要您与父级在同一域中,您就可以使用parent。添加到具有iframes的文档中:

$(function() {
    // Check if you are in an iframe, otherwise parent == self,
    // and the next check will always return true.
    function inIframe () {
        try {
            return window.self !== window.top;
        } catch (e) {
            return true;
        }
    }
    // Check if parent.url == self.url.
    function sameAsParent() {
        try {
            return parent.window.document.location.toString() === window.document.location.toString());
        } catch (e) {
            return false;
        }
    }
    if (inIframe() && sameAsParent()) {
        // You are being loaded by yourself! Redirect!
        window.location.href = 'http://some-redirect-url.com'
    }
});
相关文章: