Search code examples
javascripthtmlpostbookmarklet

Making a javascript bookmarklet that POSTs current URL


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 href to an <a> tag that I am using as the button. I want to be able to drag this tag to the bookmarks bar.

javascript: (function() {
  var url = document.location.href
  var uri = "http://localhost:3001/api/v1/links/bookmarklet?url=" + url + "&id=1"

  xhr = new XMLHttpRequest();
  xhr.open("POST", encodeURI(uri));

  xhr.send();
}());

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.

http://localhost:3000/!function()%7Bvar%20e=%22http://localhost:3001/api/v1/links/bookmarklet?url=%22+document.location.href+%22&id=1%22;xhr=new%20XMLHttpRequest,xhr.open(%22POST%22,encodeURI(e)),xhr.send()}();

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.

The HTML looks like this:

  <a href='!function(){var e="http://localhost:3001/api/v1/links/bookmarklet?url="+document.location.href+"&id=1";xhr=new XMLHttpRequest,xhr.open("POST",encodeURI(e)),xhr.send()}();' id="button">post link</a>

The incoming params for my Rails API look like this

<ActionController::Parameters {"url"=>"http://localhost:3000/!function()%7Bvar%20e=%22http://localhost:3001/api/v1/links/bookmarklet?url=%22 document.location.href %22", "id"=>"1", "xhr"=>"new%20XMLHttpRequest,xhr.open(%22POST%22,encodeURI(e)),xhr.send()}()", "format"=>:json, "controller"=>"api/v1/links", "action"=>"create_link_from_web"} permitted: false>

So it does post to the correct route in Rails but it's all messed up. Many thanks in advance for suggestions!


Solution

  • Your href attribute is considered a relative path without an explicit protocol in the string, e.g. http: or javascript:, etc. This is why it was prepending the origin domain to your URL string.

    Keep in mind that bookmarklets do not work in all browsers, so make sure you're compatible with at least your target audience.

    To correct this issue, change your HTML to

    <a href='javascript:!function(){var e="http://localhost:3001/api/v1/links/bookmarklet?url="+document.location.href+"&id=1";xhr=new XMLHttpRequest,xhr.open("POST",encodeURI(e)),xhr.send()}();' id="button">post link</a>