DanielleS Posted July 25 Share Posted July 25 (edited) Hi all, I've been trying for a few months to find a way to cross link a blog post to another website via the canonical URL. I didn't have any luck finding an existing solution. So, I wound up coming with the following script inside a blog post page. In the script, I find the existing/default Squarespace canonical URL and replace it with the external blog post link on page load. For my fellow programmers out there, what flaws does this approach have? Will this get the benefits of a canonical URL from a SEO perspective? Or because the page has to be loaded will it not work? <html> <script> function updateCanonicalURL() { // Get the <head> element const headElement = document.querySelector('head'); // Find the existing <link> tag with rel="canonical" const canonicalLinkTag = headElement.querySelector('link[rel="canonical"]'); // Update the href attribute of the <link> tag if (canonicalLinkTag) { canonicalLinkTag.setAttribute('href', 'https://www.example.com/new-page'); } else { // If the <link> tag doesn't exist, create it and append it to the <head> element const newCanonicalLinkTag = document.createElement('link'); newCanonicalLinkTag.setAttribute('rel', 'canonical'); newCanonicalLinkTag.setAttribute('href', 'https://www.example.com/new-page'); headElement.appendChild(newCanonicalLinkTag); } } // Attach the event listener to window.onload window.onload = function () { updateCanonicalURL(); }; </script> </html> From testing it out, it does update the HTML header on page load correctly. Thanks all for any input and advice! Edited July 25 by DanielleS Updated some wording. Link to comment
Jackie123 Posted Friday at 11:47 PM Share Posted Friday at 11:47 PM I'm looking for a solution as well. I won't be able to check your code, but following! Link to comment
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment