Javascript 如何检查iframe是否自行加载?

Javascript 如何检查iframe是否自行加载?,javascript,jquery,html,iframe,Javascript,Jquery,Html,Iframe,我有一个iframe来加载用户请求的内容。但是,我需要确保iframe不会自行加载,而是重定向到默认站点 这个过程必须是动态的,并且可以在任何页面上工作,因为我有多个页面在这样做,而且每个站点的自定义代码都不实用。只要你和你的父母在同一个域中,你就可以使用父母。将以下内容添加到具有iFrame的文档中: $(function() { // Check if you are in an iframe, otherwise parent == self, // and the ne

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


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

只要你和你的父母在同一个域中,你就可以使用
父母
。将以下内容添加到具有iFrame的文档中:

$(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'
    }

});