Skip to main content

How to change the shared url on the ShareThis plugin

Now that the AddThis plugin will be terminated, it's time to switch to yet another sharing platform.

The closest one that I found is ShareThis. Unfortunately, ShareThis does not have an API to change the shared info after the page has been loaded. So, we need to tinker with it a little.

What I needed was to change the url, change the description, and to open on a new page, instead of a small pop-up.

The first thing is that we need to add the data-url, data-title and data-description tags to the html element. Supposedly, this instructs the plugin to get the info from there, instead of searching somewhere else.

<div class="sharethis-inline-share-buttons" data-url="" data-title=""></div>

Next, include the js file:

<script type='text/javascript' src='https://platform-api.sharethis.com/js/sharethis.js#property=abc123456' async='async'></script>

Then, when we need to change the shared url, we must change the data attribute values from the div:

$('.sharethis-inline-share-buttons').attr({
                            'data-url' :someurl,
                            'data-title' : 'some title',
                            'data-description' : 'something else'
                        });

Lastly, we need to reload the plugin with the new data:

function shareThis() {
    if (__sharethis__ && __sharethis__.config) {
        st.open = function (url) {
            var h, w, wh, ww;
            if (!url) {
                return;
            }
            if (st.mobile) {
                return window.open(url, '_blank');
            } else if (url.indexOf('mailto:') > -1 || url.indexOf('viber') > -1) {
                return document.location = url;
            } else {
                return window.open(url, '_blank');
            }
        };
        __sharethis__.init(__sharethis__.config);
    }
}

This function must be called just after we change the data-attributes from the div element. I'm not sure why, but I found that I need to wait some time before calling the function. On my tests, I found that waiting 200ms is better.

Also, this function redefines the "open" method. On the original version, the popup is too little - it uses about 60% of the actual screen size. With the changes above, the pop-up opens on another page. I think that is way better.