Can Cross-Origin Resource Sharing headers authorize X-Domain IFRAME access?

前端 未结 1 1960
故里飘歌
故里飘歌 2020-12-03 08:30

Adjusting the height of an IFRAME to match its content page\'s height can be a real drag when the containing and content pages are not from the same domain.

Do the C

相关标签:
1条回答
  • 2020-12-03 09:32

    CORS doesn't let you do that, but you can use cross-document messaging to send strings between iframes and their parent windows even on different domains, and use that to communicate.

    Most browsers support this although Internet Explorer's way differs from the others'.

    Assuming what you want is to have the iframe announce to the parent page its desired height, you could put this in your iframe code (not tested):

    var message = {
        width: desiredWidth,
        height: desiredHeight
    };
    window.parent.postMessage(JSON.stringify(message),'*');
    

    And this in your containing page:

    function onMessage (event) {
        if (event.source != theIFrameElement.contentWindow) return;
        var message = JSON.parse(event.data);
        var desiredHeight = message.height;
        var desiredWidth = message.width;   
    }
    
    if (window.attachEvent)
        window.attachEvent('onmessage', onMessage);
    else if (window.addEventListener)
        window.addEventListener('message', onMessage, false);
    

    The attachEvent is for IE and addEventListener is for everyone else. You might want to check the target origin for security purposes, but that's the general idea.

    EDIT: Browser support for Cross-document messaging (—fsb)

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