<body></body>
<script>
  const BC0_FIRST_MSG = 'from BC0 - first';
  const BC1_FIRST_MSG = 'from BC1 - first';
  const BC2_FIRST_MSG = 'from BC2 - first';
  const BC3_FIRST_MSG = 'from BC3 - first';
  const BC0_SECOND_MSG = 'from BC0 - second';
  const BC1_SECOND_MSG = 'from BC1 - second';
  const BC2_SECOND_MSG = 'from BC2 - second';
  const BC3_SECOND_MSG = 'done';
  const BC0_TARGET_NAME = 'BC1';
  const BC1_TARGET_NAME = 'BC1';
  const BC2_TARGET_NAME = 'BC2';
  const BC3_TARGET_NAME = 'BC3';
  const MULTI_FRAME_ORDERING_TEST_CHANNEL_NAME = 'multi-frame-order';

  var bc1, bc2, bc3;
  var sentMessageCountForBc1 = 0;
  var sentMessageCountForBc2 = 0;
  var sentMessageCountForBc3 = 0;

  var bc1_handler = e => {
    window.top.logReceivedMessage(BC1_TARGET_NAME, e);
    switch(sentMessageCountForBc1) {
      case 0:
        bc3 = new BroadcastChannel(MULTI_FRAME_ORDERING_TEST_CHANNEL_NAME);
        bc3.onmessage = bc3_handler;
        bc1.postMessage(BC1_FIRST_MSG);
        break;
      case 1:
        bc1.postMessage(BC1_SECOND_MSG);
        break;
      case 2:
        bc1.close();
        return;
    }
    sentMessageCountForBc1 += 1;
  }
  var bc2_handler = e => {
    window.top.logReceivedMessage(BC2_TARGET_NAME, e);
    switch(sentMessageCountForBc2) {
      case 0:
        bc2.postMessage(BC2_FIRST_MSG);
        bc2.postMessage(BC2_SECOND_MSG);
        sentMessageCountForBc2 += 2;
        break;
      case 2:
        bc2.close();
        return;
    }
  };
  var bc3_handler = e => {
    window.top.logReceivedMessage(BC3_TARGET_NAME, e);
    switch(sentMessageCountForBc3) {
      case 0:
        bc3.postMessage(BC3_FIRST_MSG);
        break;
      case 1:
        bc3.postMessage(BC3_SECOND_MSG);
        break;
      case 2:
        bc3.close();
        return;
    }
    sentMessageCountForBc3 += 1;
  };

  window.onload = function() {
    const params = new URLSearchParams(window.location.search);
    if (params.get('id') === 'iframe1') {
      bc1 = new BroadcastChannel(MULTI_FRAME_ORDERING_TEST_CHANNEL_NAME);
      bc1.onmessage = bc1_handler;
    } else if (params.get('id')  === 'iframe2') {
      bc2 = new BroadcastChannel(MULTI_FRAME_ORDERING_TEST_CHANNEL_NAME);
      bc2.onmessage = bc2_handler;
    }
  }
</script>
