set canonical tag in javascript

To set a canonical tag using JavaScript, you need to first create a new link element and then append it to the head of your HTML document. Here's an example:

index.tsx
// Get the head element
var head = document.getElementsByTagName('head')[0];

// Create a new link element
var canonical = document.createElement('link');
canonical.setAttribute('rel', 'canonical');
canonical.setAttribute('href', 'http://www.example.com/page');

// Append the link element to the head
head.appendChild(canonical);
331 chars
11 lines

In this example, we first grab the head element using getElementsByTagName, and then create a new link element using document.createElement. We set the rel attribute to "canonical" and the href attribute to the URL we want to set as the canonical URL for our page.

Finally, we append the link element to the head using appendChild.

Note that if your page already has a canonical tag set in the HTML, appending a new one via JavaScript may not be effective. It's generally best to set the canonical tag directly in the HTML source code whenever possible.

gistlibby LogSnag