title: Making a javascript bookmarklet that POSTs current URL
body: <p>I'm trying to make a javascript bookmarklet that posts the current URL to my API. For example, something similar to what the Instapaper bookmarklet does. I wrote the following script, have passed it through a minifier and added it as the <code>href</code> to an <code>&lt;a&gt;</code> tag that I am using as the button. I want to be able to drag this tag to the bookmarks bar.</p>
  
  <pre><code>javascript: (function() {
    var url = document.location.href
    var uri = "http://localhost:3001/api/v1/links/bookmarklet?url=" + url + "&amp;id=1"
  
    xhr = new XMLHttpRequest();
    xhr.open("POST", encodeURI(uri));
  
    xhr.send();
  }());
  </code></pre>
  
  <p>Currently I am just testing this out on my local server at localhost:3001 and am running my app on localhost:3000. If I press the button whilst on my app (on localhost:3000) it does make the post request but it adds the script itself to address bar on top of the current url. </p>
  
  <p><code>http://localhost:3000/!function()%7Bvar%20e=%22http://localhost:3001/api/v1/links/bookmarklet?url=%22+document.location.href+%22&amp;id=1%22;xhr=new%20XMLHttpRequest,xhr.open(%22POST%22,encodeURI(e)),xhr.send()}();</code></p>
  
  <p>If I drag the button to the bookmarks bar and click it from another site, it redirects back to localhost:3000 and does the same thing. Am I missing something obvious here? I can't really find any instructions on the web on how to implement a bookmarklet to post a current URL. </p>
  
  <p>The HTML looks like this:</p>
  
  <pre><code>  &lt;a href='!function(){var e="http://localhost:3001/api/v1/links/bookmarklet?url="+document.location.href+"&amp;id=1";xhr=new XMLHttpRequest,xhr.open("POST",encodeURI(e)),xhr.send()}();' id="button"&gt;post link&lt;/a&gt;
  </code></pre>
  
  <p>The incoming params for my Rails API look like this</p>
  
  <pre><code>&lt;ActionController::Parameters {"url"=&gt;"http://localhost:3000/!function()%7Bvar%20e=%22http://localhost:3001/api/v1/links/bookmarklet?url=%22 document.location.href %22", "id"=&gt;"1", "xhr"=&gt;"new%20XMLHttpRequest,xhr.open(%22POST%22,encodeURI(e)),xhr.send()}()", "format"=&gt;:json, "controller"=&gt;"api/v1/links", "action"=&gt;"create_link_from_web"} permitted: false&gt;
  </code></pre>
  
  <p>So it does post to the correct route in Rails but it's all messed up. Many thanks in advance for suggestions!</p>