title: Javascript communicating cross-domain to parent window of iframe
body: <p>I have written a tool for taking notes, grabbing images from web pages. It loads itself as a iFrame within the current window by using a javascript bookmark:</p>
  
  <pre><code>javascript:(function(){   _my_script=document.createElement('SCRIPT');   _my_script.type='text/javascript';   _my_script.src='http://basereality.test/js/bookmarklet.js?rand='+(Math.random());   document.getElementsByTagName('head')[0].appendChild(_my_script); })();
  </code></pre>
  
  <p>I want to be able to close the tool by removing the iFrame from the parent window, when the user clicks on a close button. </p>
  
  <p>What is the easiest way of doing this - Is it possible to close an iFrame within itself?</p>
  
  <p>I've tried using cross-domain message posting. I have cross-domain posting working from the parent window to the child iFrame, but doesn't work from the iFrame to the parent window.</p>
  
  <p>The code I have so far (which presumably contains the problem) is as follows.</p>
  
  <p>In the parent window through the dynamically loaded Javascript:</p>
  
  <pre><code>function    addiFrame(domain){
      var iframe_url = "http://" + domain + "/bookmarklet";
  
      var div = document.createElement("div");
      div.id = bookmarkletID;
  
      var str = "";
  
      iframe_url += "?description=" + encodeURIComponent(document.title);
      iframe_url += "&amp;amp;URL=" + encodeURIComponent(document.URL);
  
      str += "&lt;div&gt;";
      str += "&lt;iframe frameborder='0' class='toolPanelPopup dragTarget' style='z-index: 1000'  name='bookmarklet_iframe' id='bookmarklet_iframe' src='" + iframe_url + "' width='550px' height='255px' style='textalign:right; backgroundColor: white;' /&gt;";
  
      str += "&lt;/div&gt;";
  
      div.innerHTML = str;
  
      document.body.insertBefore(div, document.body.firstChild);
  }
  
  
  function jQueryLoadedCallback(){
  
      jQueryAlias = jQuery.noConflict();
      jQueryAlias('#' + bookmarkletID).bind('basereality.removeFrame', removeFrame);
  }
  
  function removeFrame(){
      alert("Calling remove frame");
      $("#" + bookmarkletID).remove();
  }
  </code></pre>
  
  <p>In the iFrame, the button to close the iFrame calls:</p>
  
  <pre><code>function removeFrame(){
      var params = {};
      params.message = 'basereality.removeFrame';
      parent.postMessage(params, "*");
  }
  </code></pre>
  
  <p>The removeFrame call in the iFrame doesn't result in the removeFrame being called in the parent window. </p>
  
  <p>So how should I actually remove the iFrame.</p>