Adding Meta Tags using JavaScript


You may find yourself in a situation where you need to add a custom meta tag or Canonical URL to your <head> template, and for any number of reasons, this can't be 'hard coded' into the <head> tag - it needs to be dynamic based on each individual page. Some situations where this might arise are:

  • If you are using Shareaholic on a subpath of a root domain you own (like, and want to verify the subpath. You can use the following custom JavaScript snippet to add your Shareaholic Site ID to the <head> tag of the root domain, which will enable you to verify your site.
  • If you want to specify the URL that the OpenGraph URL and/or Shareaholic:url meta tag points to, if it differs from your current permalink. This can be helpful in retrieving shares from different permalink paths.
  • You are a marketer or non-Dev using Google Tag Manager, and wish to insert the Shareaholic metatags on your site. This method will allow you to do so without having to contact your development team.

Fortunately, you can use some custom JavaScript to automatically and dynamically add these metatags to all of your pages quickly and easily! This code is also incredibly adaptable - you can set pretty much any meta tag and value that you'd like!

NOTE: If you are using this code snippet on a page where Shareaholic is installed, this code snippet must be included before Shareaholic.js loads on your page, so it must come before your Shareaholic Setup Code. 

No matter what your particular use case is, the custom JavaScript code will follow the same basic structure. Here is an example of this custom code snippet used to set the og:url meta tag to the current URL displayed in the address bar:

<script type='text/javascript' data-cfasync='false'>
  var link=document.createElement('meta');"og:url";

To set your Shareaholic:URL meta tag instead, simply replace the "og:url" in the snippet above with "shareaholic:url"

If you want to use this code to add the Shareaholic Site ID to your Root Domain for verification purposes, you can modify it as follows:

<script type='text/javascript' data-cfasync='false'>
  var link=document.createElement('meta');"shareaholic:site_id";
  link.content="[[YOUR SITE ID]]";

To break it down a little, this code first creates a meta tag element, then we specify the name of the meta tag, as well as the content of the meta tag. Finally, we append this newly created meta tag element to your <head> tag on your page, and you're off and running!

Remember: If you are using this code on a page that is also loading Shareaholic, this code snippet must come before the line that loads Shareaholic.js in the header, or else the code snippet will not work.


Was this article helpful?