Search code examples
javascriptif-statementalertbookmarkletbookmarks

Javascript Bookmarklet If-Else


I'm trying to write a bookmarklet that detects if the user is on an already parsed page and if he isn't values should be passed along to an API.

if (window.location.indexOf("thequeue.org") >= 0) {
    alert("Drag the Bookmarklet in your Brookmarks Bar!");
} else {
    location.href = 'http://thequeue.org/r?id=' + encodeURIComponent(location.href) + '&title=' + document.title;
}

There are few tutorials on Bookmarklets in general, but I have found this conversion tool: http://jasonmillerdesign.com/Free_Stuff/Instant_Bookmarklet_Converter, which gave me this:

javascript:(function(){if(window.location.indexOf(%22queue.org%22)%20%3E%3D%200)%0A%20%20%20%20%20%20%20%20%20%20%20%20%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20alert(%22your%20url%20contains%20the%20name%20franky%22)%3B%0A%20%20%20%20%20%20%20%20%20%20%20%20%7D%20else%20%7B%0Alocation.href%3D'http%3A%2F%2Fthequeue.org%2Fr%3Fid%3D'%2BencodeURIComponent(location.href)%2B'%26title%3D'%2Bdocument.title%3B%0A%7D}());

However the bookmarklet stops working completely. I can confirm that this works: javascript:location.href='http://thequeue.org/r?id='+encodeURIComponent(location.href)+'&title='+document.title;

What am I doing wrong?


Solution

  • This should work for you:

    javascript:(function(){if(location.href.indexOf("thequeue.org/")>=0){alert("Drag the Bookmarklet in your Brookmarks Bar!");}else{location.href='http://thequeue.org/r?id='+encodeURIComponent(location.href)+'&title='+document.title;}})();
    

    Notice that i changed the if sentence slightly to make it more robust.