简体   繁体   English

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

[英]How to check if iframe is loaded by itself?

I have an iframe that loads what a user requests. 我有一个加载用户请求的iframe。 However, I need to make sure that the iframe does not load itself and is instead redirected to a default site. 但是,我需要确保iframe不会加载自身,而是重定向到默认站点。

The process has to be dynamic and work on any page, as I have multiple pages doing this, and custom code for each site wouldn't be practical. 该过程必须是动态的,并且可以在任何页面上工作,因为我要在多个页面上执行此操作,并且每个站点的自定义代码都不切实际。

As long as you are on the same domain as your parent, you can use parent . 只要您与父母位于同一个域中,就可以使用parent Add to the documents having iframes: 添加到具有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'
    }

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM