postMessage still broken on IE11?

后端 未结 4 1215
春和景丽
春和景丽 2020-12-02 15:02

It seems that window.postMessage is still broken on IE 11 when the message is

  • between a window and a child popup/tab with window.open
  • when it\'s sent
4条回答
  •  死守一世寂寞
    2020-12-02 15:11

    Is it broken? Well, sort of.

    I tried various ideas and couldn't get the code in your jsFiddle to work. Looking at this MSDN Blog post, we find that postMessage only works between IFrames in older versions of IE, which has yet to be fixed for IE 11.

    That article links to a demo of the problem. There are a couple of workarounds that involve calling scripts on the window.opener. However, as that blog states (emphasis mine):

    Unfortunately, this workaround often isn't possible, because same-origin-policy dictates that the popup window and the window.opener page must be from the same origin in order to call each other's script functions.

    So it looks like the only way to do this is something like this, where the child is hosted in an IFrame in the parent. I have created a similar demo here, based on the code in yours. It's pretty simple, but posts a message to the contentWindow of the IFrame, which in turn responds.

    I see the recommendation to use MessageChannel instead, but I also wonder if using Web Workers might be worth investigating, though their use would of course depend on the nature of your task. There is also the answer to this question, where the IFrame approach was used, but a jQuery UI dialog was used to display it - I would imagine you could do the same thing with modals in Bootstrap if you prefer that.


    For reference:

    HTML

    
    

    Parent script

    var wnd;
    
    $(document).ready(function() {
        $('#log').append('listening...');
    
        wnd = $('#iframe')[0].contentWindow;
    
        window.addEventListener('message', function(e){
          $('#log').append('
    Received message: ' + JSON.stringify(e.data)); }, false); $('#post-message-button').click(function() { if(!wnd){ return; } $('#log').append('
    sending...'); wnd.postMessage('Hello?', 'http://jsbin.com'); }); });

    Child HTML and JS

    
    
    
    
    
    JS Bin
    
    
      
    
    
    
    
    

提交回复
热议问题