Is there a client-side way to detect X-Frame-Options?

后端 未结 8 714
温柔的废话
温柔的废话 2020-12-28 12:16

Is there any good way to detect when a page isn\'t going to display in a frame because of the X-Frame-Options header? I know I can request the page serverside and look for

相关标签:
8条回答
  • 2020-12-28 12:57

    This can be achieved through

    a) Create a new IFrame through CreateElement

    b) Set its display as 'none'

    c) Load the URL through the src attribute

    d) In order to wait for the iframe to load, use the SetTimeOut method to delay a function call (i had delayed the call by 10 sec)

    e) In that function, check for the ContentWindow length.

    f) if the length > 0, then the url is loaded else URL is not loaded due to X-Frame-Options

    Below is the sample code:

    function isLoaded(val) {
    var elemId = document.getElementById('ctlx');
    if (elemId != null)
        document.body.removeChild(elemId);
    
    
    var obj= document.createElement('iframe');
    
    obj.setAttribute("id", "ctlx");
    
    obj.src = val;
    obj.style.display = 'none';
    
    document.body.appendChild(obj);
    
    setTimeout(canLoad, 10000);  
    
    }
    
    function canLoad() {
    //var elemId = document.getElementById('ctl100');
    var elemId = document.getElementById('ctlx');
    if (elemId.contentWindow.length > 0) {
        elemId.style.display = 'inline';
    
    }
    
    else {
        elemId.src = '';
        elemId.style.display = 'none';
        alert('not supported');
    }
    }
    
    0 讨论(0)
  • 2020-12-28 13:02

    At least in Chrome, you can notice the failure to load because the iframe.onload event doesn't trigger. You could use that as an indicator that the page might not allow iframing.

    0 讨论(0)
提交回复
热议问题