Replace existing canonical tag with javascript or jquery
Asked Answered
B

2

7

I'm wanting to create a widget for Adobe Muse that replaces the canonical tags that Muse automatically generates.

I know that this will not work with most bots because they don't run any scripts when crawling pages, but I have read that Google's bot does run scripts when it crawls.

I found many questions on how to replace the href from a links but I couldn't seem to find any questions on replacing the href URL of a canonical tag. I'm almost positive this is where I start... I just don't know how to finish it:

<script>
    $(document).ready(function() {
         $('link[rel=canonical]').attr('href' 'NEW_LINK');
    }
</script>
Bronchi answered 16/3, 2015 at 0:9 Comment(3)
Exactly what are you wanting the script to do? Are you trying to completely replace a <link> tag, are you trying to change the rel attribute of a pre-existing <link> tag, or something else?Washbowl
I'm wanting to replace the href urlBronchi
I reread your question; now I get what you're asking. As I was typing that, Moogs posted a working solution. See below.Washbowl
E
15
$('link[rel="canonical"]').attr('href', 'NEW_HREF_GOES_HERE');
Efficacious answered 16/3, 2015 at 0:16 Comment(2)
Okay, so this should have worked, right? <script> $(document).ready(function() { if (canonical = $('link[rel=canonical]').attr('href', 'bar')); } </script>Bronchi
@JohnRPerry a couple of issues: in your if statement you are assigning the jquery object to canonical variable. If you want to compare use triple equality signs. The other issue is you are setting the href value in the if statement. Although this does set it, it's bad practice because it's inside the if statement. My question to you is, what are you comparing? what is the canonical variable?Efficacious
R
9

And for those who are fans of vanilla JS:

const canonical = document.querySelector('link[rel="canonical"]');
if (canonical !== null) {
  canonical.href = 'NEW_HREF_GOES_HERE';
}

If cross-browser compatibility is important, and you're not using a transpiler, change const to var.

Renaldo answered 30/3, 2019 at 21:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.