Adding a “share to mastodon” link to any web site

adding-a-“share-to-mastodon”-link-to-any-web-site

I just added a “share to mastodon” link to my blog at ChristianHeilmann.com. Ages ago I added a “share to Twitter” link, as there is a URL you can send Tweet content to that works:

http://twitter.com/share?url={URL}&text={text}?&via={twitter_handle}

With Mastodon, it wasn’t as easy as it is a federated service and there is not one URL. So I had to find a way to ask people for their service URL, and then store it somehow.

I’ve seen quite a few solutions for this, but I really wanted a bare-bones one that you can style any way you want. So here’s mastodon-share for you.

In order to add a “share to mastodon” link, all you need to do is to add a link with the class “.mastodon-share” and include the script:

 href="#" target="mastodon" class="mastodon-share">
Share to Mastodon


The script is ridiculously simple, if you check it out:

// Grab link from the DOM
const button = document.querySelector('.mastodon-share');

// When a user clicks the link
button.addEventListener('click', (e) => {

// If the user has already entered their instance and it is in localstorage
// write out the link href with the instance and the current page title and URL
if(localStorage.getItem('mastodon-instance')) {
  button.href = `
    https://${localStorage.getItem('mastodon-instance')}/
    share?text=${encodeURIComponent(document.title)}
    %0A${encodeURIComponent(location.href)}
  `;
// otherwise, prompt the user for their instance and save it to localstorage
} else {
    e.preventDefault();
    let instance = window.prompt(
      'Please tell me your Mastodon instance'
    );
    localStorage.setItem('mastodon-instance', instance);
}
});

You can try it out on GitHub.

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
csol-test-post-–-do-not-publish

CSOL TEST POST – DO NOT PUBLISH

Next Post
the-top-9-social-networks-for-businesses

The Top 9 Social Networks For Businesses

Related Posts