How to add canonical url via JavaScript

<script type='text/javascript'>
  var link = !!document.querySelector("link[rel='canonical']") ? document.querySelector("link[rel='canonical']") : document.createElement('link');
  link.setAttribute('rel', 'canonical');
  link.setAttribute('href', location.protocol + '//' + location.host + location.pathname);
  document.head.appendChild(link);
</script>

Add a Comment

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