<script>
  window.iframeLoaded = window.iframeLoaded || function(iframe) {
    try {
      iframe.contentWindow.pdMessageListeners = [];
      iframe.contentWindow["addPDMessageListener"] = function(listener){
        iframe.contentWindow.pdMessageListeners.push(listener);
      }
      iframe.contentWindow.addEventListener("message", function(event){
        iframe.contentWindow.pdMessageListeners.forEach(function(listener){
          listener(event);
        });
      }, false);
      iframe.contentWindow.ready = true;
      iframe.contentWindow["triggerPDEvent"] = function(eventInfo) {
        $(document).trigger('pd_event', eventInfo);
      }
    } catch (e) {
      console.log(e)
    }
  }

  {%if this.isStreaming%}
  !function(){
    var comm_manager = Jupyter.notebook.kernel.comm_manager
    var contentWindow = null
    comm_manager.register_target("{{this.commId}}", function (comm, msg) {
        return comm.on_msg(function(msg){
            if (!contentWindow){
              var n = $("#mapframe{{prefix}}");
              if (n.length>0){
                contentWindow = n[0].contentWindow;
              }else{
                console.log("Unable to find contentWindow");
              }
            }
            if (contentWindow && contentWindow.ready){
              contentWindow.postMessage(msg.content.data, "*");
            }else{
              var deferredData = msg.content.data;
              var ival = setInterval(function(){
                if (contentWindow && contentWindow.ready){
                  contentWindow.postMessage(msg.content.data, "*");
                  clearInterval(ival);
                }
              }, 1000 );
            }
        });
    });
  }();
  {%endif%}
</script>
<iframe id="mapframe{{prefix}}" style='width:{{prefwidth}}px;height:{{prefheight}}px' srcdoc='' onload="iframeLoaded(this)"></iframe>
<script>
  var iframe = document.getElementById('mapframe{{prefix}}');
  iframe.setAttribute('srcdoc', atob('{{body|btoa}}'));
</script>
{%if this.isStreaming%}
<div pd_refresh_rate="{{this.options.get('refresh', 1000)}}" class="no_loading_msg">
    <pd_script>
from ipykernel.comm import Comm
from pixiedust.display.streamingDisplay import *
cellId = "{{this.options["cell_id"]}}"
entity = activesStreamingEntities[cellId] if cellId in activesStreamingEntities else None
if entity is not None:
  comms = Comm(target_name="{{this.commId}}", data={}) if not hasattr(entity, "comms") else entity.comms
  entity.comms = comms
  metadata = entity.getMetadata();
  comms.send({
    "data": entity.getNextData(),
    "type": metadata.get("type", "circle"),
    "layout": metadata.get("layout", {}),
    "paint": metadata.get("paint", {}),
    "fitbounds": metadata.get("fitbounds", True)
  })
    <pd_script>
</div>
{%endif%}