5

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>
John R Perry
  • 3,916
  • 2
  • 38
  • 62
  • 1
    Exactly what are you wanting the script to do? Are you trying to completely replace a `` tag, are you trying to change the `rel` attribute of a pre-existing `` tag, or something else? – IronFlare Mar 16 '15 at 00:14
  • 1
    I'm wanting to replace the href url – John R Perry Mar 16 '15 at 00:15
  • I reread your question; now I get what you're asking. As I was typing that, Moogs posted a working solution. See below. – IronFlare Mar 16 '15 at 00:17

2 Answers2

13
$('link[rel="canonical"]').attr('href', 'NEW_HREF_GOES_HERE');
Miguel Mota
  • 20,135
  • 5
  • 45
  • 64
  • Okay, so this should have worked, right? – John R Perry Mar 16 '15 at 00:43
  • @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? – Miguel Mota Mar 16 '15 at 00:48
6

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.

crenshaw-dev
  • 7,504
  • 3
  • 45
  • 81