set canonical url in javascript

To set a canonical URL in JavaScript, you can use the HTML DOM querySelector() and setAttribute() methods to access the head section of the page and set a link element with a rel attribute of "canonical", and a href attribute with the desired URL.

Here's an example code block:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>My Page</title>
  <script>
    const canonicalLink = document.querySelector('link[rel="canonical"]') || document.createElement('link');
    canonicalLink.setAttribute('rel', 'canonical');
    canonicalLink.setAttribute('href', 'https://example.com/my-page');
    document.head.appendChild(canonicalLink);
  </script>
</head>
<body>
  <!-- Rest of your HTML content -->
</body>
</html>
449 chars
17 lines

This code first checks if a link element with rel="canonical" already exists in the document's head section. If it does, it assigns it to the canonicalLink variable. If it does not exist, it creates a new link element.

Then, it sets the rel attribute to "canonical" and the href attribute to the desired URL (in this case, https://example.com/my-page).

Finally, it appends the link element to the head section of the document.

Note that setting a canonical URL is an important aspect of search engine optimization (SEO) as it helps search engines identify the main version of a page and consolidate link equity to that page.

gistlibby LogSnag