How to set canonical tag dynamic url in javascript?

To set a dynamic canonical tag URL using JavaScript, you will need to retrieve the URL of the current page and use it to dynamically set the href attribute of the canonical link element. Here is an example:

<link rel="canonical" href="">
  <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>

In this example, we retrieve the URL of the current page using window.location.href and store it in the canonicalUrl variable. Then, we create a new link element and set its rel attribute to 'canonical'. Next, we set the href attribute of the link element to the canonicalUrl variable, which contains the URL of the current page. Finally, we append the link element to the head of the HTML document.

By using window.location.href, the canonical URL will always be set dynamically to match the URL of the current page. This approach is useful if you have a dynamic website where the URL structure changes based on user input or other factors.

Either you can use the given above example or following code.

const canonicalUrl = window.location.href;
const link = document.createElement('link');
link.rel = 'canonical';
link.href = canonicalUrl;
document.head.appendChild(link);

Learn how to dynamically set the canonical tag URL using JavaScript with this easy-to-follow guide. This approach is useful for dynamic websites where the URL structure changes based on user input or other factors. Follow the step-by-step instructions to ensure that search engines properly recognize the preferred version of your web page.

Leave a Reply

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