Mohan S Nayaka
Mohan S Nayaka

Reputation: 373

How do I distribute my bookmarklet conveniently?

I just wrote my first bookmarklet. It is simple js code which takes the current page's URL and does a POST request to submit it to another page.

The problem is that I need to share this on a blogging platform (quora.com) that does not allow HTML. Thus, I need to post a link to my bookmarklet on a different website and provide a link to that. I'd like to be able to provide a single link that folks can drag to their bookmarks bar.

This is the bookmarklet code.

javascript:(function() {
    var msg = window.jQuery.ajax({url:'https://www.quora.com/api/logged_in_user',async:false,type:'GET'});
    var username = undefined;
    if (msg) {
        username = window.jQuery.parseJSON(msg.responseText.replace('while(1);',''));
    window.jQuery.post('https://my-website',
        {'answer_1':window.location.href,'submitter':username.name});
    alert (username.name + ' nominates  ' + window.location.href);
}})();

Upvotes: 7

Views: 2701

Answers (1)

Shardul Vikram Singh
Shardul Vikram Singh

Reputation: 226

First, you need to escape the special characters \ , ` , $ in your bookmarklet code and store it in a template string. Then, you can create an anchor tag and set its href attribute equal to your template string. This enables users to easily drag the link into their bookmarks bar. Subsequently, they can execute your code by simply clicking on the bookmark.

var bookmarkletString = `javascript:(function() {
    var msg = window.jQuery.ajax({url:'https://www.quora.com/api/logged_in_user',async:false,type:'GET'});
    var username = undefined;
    if (msg) {
        username = window.jQuery.parseJSON(msg.responseText.replace('while(1);',''));
    window.jQuery.post('https://my-website',
        {'answer_1':window.location.href,'submitter':username.name});
    alert (username.name + ' nominates  ' + window.location.href);
}})();`;
document.querySelector("#bookmarklet").href = bookmarkletString;
<h1>Drag This Link into your Bookmarks Toolbar</h1>

<a id="bookmarklet">Your Bookmarklet Name</a>

Upvotes: 1

Related Questions