The Simplest (and Most Performant) Way to Offer Sharing Links for Social Media

This past summer, I wrote The Essential Meta Tags for Social Media about how developers can prepare web pages to optimize their appearance when shared on social media. But what about creating the links to let users share these web pages? Facebook, Twitter, and LinkedIn offer numerous ways to do this, some involving button generators and others that require external JavaScript. To avoid all of that, though, you can create your own links to share web pages. And the best part is that it’s simple to do yourself. Here’s how.

Basic Concept: Just a Link

When sharing web pages using links, you’re essentially submitting a GET request (i.e. clicking a link) to a URL provided by each social media service. Then, by appending a series of name/value pairs (query parameters like ?title=Title) to the end of this URL, you can specity the URL of the web page you want to share and, sometimes, additional information.

Now, certain symbols in GET requests known as “reserved characters”, need to be encoded properly so as not to interfere with normal browser functions. These characters are subject to “percent-encoding” – that is, they are represented in query parameters with a “%” followed by a two-digit hex code. These are the reserved characters and their percent-encoded equivalents.

! # $ & ' ( ) * +
%21 %23 %24 %26 %27 %28 %29 %2A %2B
, / : ; = ? @ [ ]
%2C %2F %3A %3B %3D %3F %40 %5B %5D

Note: A space can be represented by “%20” or “+”.

Of course, there’s no need to memorize these hex codes. There are many resources that provide conversions (Bing has one built into the search engine) and, as you will soon see, JavaScript can also handle the heavy lifting in this regard. Let’s look at a few of the more popular social media services and learn how we can share web pages through them.

Facebook

Per their Developer’s Guide, Facebook specifies the following URL to submit GET requests when sharing a web page:

https://www.facebook.com/dialog/share

While there are four query parameters available, only two are required: the URL of the web page that you want to share and an App ID, which developers can obtain by registering at Facebook. If you don’t have an App ID, the registration process is not onerous, but there’s no need to bother when an even simpler solution exists.

Facebook’s original method of sharing web pages, without the required App ID, is no longer mentioned in any of their documentation, but it’s still supported. In fact, with countless web sites using this method, I can’t imagine it would be deprecated anytime soon. This URL is:

https://www.facebook.com/sharer.php

The only parameter available is “u”, which is used to specify the URL of the web page you want to share. Here’s an example that shares the home page of CSS-Tricks on Facebook – go ahead, cut-and-paste into a browser to see the result.

https://www.facebook.com/sharer.php?u=https%3A%2F%2Fcss-tricks.com%2F

As previously explained, the URL shared is necessarily percent-encoded. Also, note how “?” designates the start of the first query parameter. Subsequent query parameters are separated by “&” as will be seen shortly.

Twitter

Twitter refers to sharing a web page via URL as a Tweet Web Intent – the URL to use is:

https://twitter.com/intent/tweet

Unlike Facebook, where only the web page being shared can be specified, Twitter allows you to tack on some text and any number of hashtags. Users will have the opportunity to edit all of this before tweeting, but it gives them a head start in case they can’t be bothered. For example, let’s say you wanted to tweet the following information:

parameter value
url https://openvpn-client.megasupersecretplace.com:5757/
text Tips, Tricks, and Techniques on using Cascading Style Sheets.
hashtags css html

The URL for that, with the query parameters percent-encoded and line breaks added for clarity, is:

https://twitter.com/intent/tweet
?url=https%3A%2F%2Fcss-tricks.com%2F
&text=Tips%2C+Tricks%2C+and+Techniques+on+using+Cascading+Style+Sheets.
&hashtags=css,html

And that gives you:

You’ll notice that Twitter pre-selects the text, which allows for easy editing by the user. And, remember, the tweet needs to be under 140 characters, so best not supply any copy that’s too long. In the interest of simplicity, I omitted discussing three lesser-used parameters, which can be found described in detail at Twitter’s Developers Documentation. These additional parameters allow you to specify the username associated with the tweet, suggested related usernames, and an ID of a related tweet.

LinkedIn

The URL to use when sharing on LinkedIn is:

https://www.linkedin.com/shareArticle

In total, there are five parameters available as detailed by this chart taken from LinkedIn’s Developers documentation:

Parameter Description Max Length Required
url The url-encoded URL of the page that you wish to share. 1024 Yes
mini A required argument whose value must always be: true 4 Yes
title The url-encoded title value that you wish you use. 200 No
summary The url-encoded description that you wish you use. 256 No
source The url-encoded source of the content (e.g. your website or application name) 200 No

In addition to the URL of the web page that you want to share, another query parameter called “mini” is required. But, as you can see, its value never changes, so we can hardcode that into the URL. To demonstrate, let’s share the following on LinkedIn:

parameter value
url https://openvpn-client.megasupersecretplace.com:5757/
title CSS-Tricks
summary Tips, Tricks, and Techniques on using Cascading Style Sheets.
source CSS-Tricks

This gives the following URL – again, line breaks added for clarity:

https://www.linkedin.com/shareArticle
?mini=true
&url=https%3A%2F%2Fwww.css-tricks.com%2F
&title=CSS-Tricks
&summary=Tips%2C+Tricks%2C+and+Techniques+on+using+Cascading+Style+Sheets.
&source=CSS-Tricks

While not mentioned explicitly in their documentation, if the “title” parameter is omitted, LinkedIn will grab this content from the Open Graph tag <meta property="og:title"> from the shared page. Similarly, if the “summary” parameter is omitted, the Open Graph tag <meta property="og:description"> is used. As for the “source” parameter, nothing in the documentation specifies how this value is used or displayed when sharing a web page – it looks as if it can be safely ignored.

Knowing all of this, if the web page being shared has the proper complement of Open Graph tags, simply specifying the URL will suffice as the “title” and “summary” parameters will be suitably populated.

Putting It All Together

Now that we know the syntax to use when sharing web pages on social media, how exactly can we implement this code? Perhaps the most common way is simply listing a group of sharing links styled appropriately with CSS:

<ul>
  <li><a href="https://www.facebook.com/sharer.php?..." target="blank"><img src="facebook-icon.png" alt="Share Page on Facebook" /></a></li>
  <li><a href="https://twitter.com/intent/tweet?..." target="blank"><img src="twitter-icon.png" alt="Share Page on Twitter" /></a></li>
  <li><a href="https://www.linkedin.com/shareArticle?..." target="blank"><img src="linkedin-icon.png" alt="Share Page on LinkedIn" /></a></li>
</ul>

The adding of target="_blank" in the anchor tag allows the sharing dialog to appear in a new window or tab, which works well on all devices, from desktop to mobile.

But hard-coding these links, with the percent-encoding of the query parameters, can be tedious and error prone. For any web page dynamically served by a CMS, this would be the perfect opportunity to have this data crunching performed on the server side and inserted where needed in the HTML.

Another option is to use the Social Media Sharing: HTML Links Generator that I created on CodePen. This allows you to enter any or all of the necessary parameters we’ve just reviewed, and it will output the appropriate HTML for you to insert into your own code.

See the Pen Social Media Sharing: HTML Links Generator by Adam Coti (@adamcoti) on CodePen.

As a freelance web developer working almost exclusively on the front-end, I’ve opted to use JavaScript/jQuery functionality that, without customization, works as a turnkey solution for my projects. This way, I can be assured that all sharing links will be properly handled, whether I’m working on a static web site, customizing WordPress themes, or handing off templates to be integrated into a CMS.

This is the HTML I use, with classes designating the particular sharing service. In the JavaScript, the function setShareLinks(), which attaches click events to the share buttons, is called when the Document Object Model (DOM) is ready:

<ul>
  <li class="social-share facebook"><img src="facebook-icon.png" alt="Share Page on Facebook" /></li>
  <li class="social-share twitter"><img src="twitter-icon.png" alt="Share Page on Twitter" /></li>
  <li class="social-share linkedin"><img src="linkedin-icon.png" alt="Share Page on LinkedIn" /></li>
</ul>
function socialWindow(url) {
    var left = (screen.width - 570) / 2;
    var top = (screen.height - 570) / 2;
    var params = "menubar=no,toolbar=no,status=no,width=570,height=570,top=" + top + ",left=" + left;
    window.open(url,"NewWindow",params);
}

function setShareLinks() {
    var pageUrl = encodeURIComponent(document.URL);
    var tweet = encodeURIComponent(jQuery("meta[property='og:description']").attr("content"));
    
    jQuery(".social-share.facebook").on("click", function() {
        url = "https://www.facebook.com/sharer.php?u=" + pageUrl;
        socialWindow(url);
    });

    jQuery(".social-share.twitter").on("click", function() {
        url = "https://twitter.com/intent/tweet?url=" + pageUrl + "&text=" + tweet;
        socialWindow(url);
    });

    jQuery(".social-share.linkedin").on("click", function() {
        url = "https://www.linkedin.com/shareArticle?mini=true&url=" + pageUrl;
        socialWindow(url);
    })
}

The URL of the current web page is easily acquired by reading a property of the document object. And, for Twitter, the Open Graph tag <meta property="og:description"> conveniently provides appropriate content for a default tweet.

Now, at the request of some of my clients, I launch the newly formed URL in a specially sized secondary (pop-up) window by utilizing window.open(). On most desktop browsers, this window is positioned horizontally and vertically centered on the screen. Interestingly enough, if a user is logged in to their social media account, Facebook and LinkedIn will resize this secondary window to the necessary dimensions. Twitter doesn’t, so I use a default width and height that provides it with enough real estate. As far as responsiveness, tablets and mobile devices interpret the secondary window as a new tab. A demo of this functionality can be found on CodePen.

See the Pen Social Media Sharing: Automated Link Creator by Adam Coti (@adamcoti) on CodePen.

But using a pop-up window, while once common, is now frowned upon for accessibility reasons. A simple solution is to set the variable params to an empty string in the above JavaScript. Doing so launches the URL in a new window or tab depending on the user’s browser setting.

Conclusion

As the gruesome saying goes, there are many ways to skin a cat. The above technique is simply my preferred method. You may have a better, more optimized way. Perhaps using data attributes in the HTML (to specify hashtags, for example) that can be read by JavaScript and appended as a query parameter where needed. Hopefully this can at least serve as inpiration for your own implementation.