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:
449 chars17 linesThis 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