Streaming live at 10am (PST)

DOM element not being added by my script

Hi there!

I’m trying to add a conditional canonical link in head custom code of a Blog Post Template page, using the method suggested by @bart here: https://forum.webflow.com/t/conditional-canonical-link-in-head-custom-code/33957/7

<script>
 const curl = "{{wf {&quot;path&quot;:&quot;canonical-link&quot;,&quot;type&quot;:&quot;Link&quot;\} }}"
 if (curl != "") {
  link=document.createElement('link');
  link.href='{{wf {&quot;path&quot;:&quot;canonical-link&quot;,&quot;type&quot;:&quot;Link&quot;\} }}';
  link.rel='canonical';
  document.getElementsByTagName('head')[0].appendChild(link);
}
</script>

When viewing the source code of the page, the script is there, but the canonical link is never added to the head section, even when the condition is verified.

I must do something wrong but I can’t find what. Any help would be greatly appreciated, thank you! :pray:

Here’s the preview link:
https://preview.webflow.com/preview/guildeur?utm_medium=preview_link&utm_source=designer&utm_content=guildeur&preview=c48cae738e2e81e1760c92d79e1cd948&pageId=5ec12ef64dcf2c1a7828254e&itemId=5ec12f0b1f3b9f3cf6cabb4a&mode=preview

Maybe it’s useless… but I’m replying to my own post in case it might make it a bit more visible :smiley:
I’m still stuck with this issue.

Thank you!

Hi Phil your script is wrong, link is never defined anywhere so it will give you an undefined error

1 Like

Thank you for your help @pietrofalco!

Could you point me at what I’m doing wrong?
Here is the custom code I added to my template settings:

As you can see, it’s similar to what Bart was sharing at https://forum.webflow.com/t/conditional-canonical-link-in-head-custom-code/33957/7 . Is there something wrong with this method, or is it me who introduced a bug?

Thank you!

Your code is invalid simply because link is not a valid variable, it’s not declared anywhere, so it’s undefined. To be clear line 4 causes the error “Type error: link is undefined”. Have you seen line 2? there you declared a constant, link must exists so the correct way is const link = document.create and etc etc etc

@pietrofalco thanks a lot for your help!
It turned out that the link was properly generated, so I suppose that the original issue was due to a deployment issue with Webflow. I’m sorry for wasting your time :frowning:

I’m really a noob at js, but from what I read don’t think that declaring the object is required. Assigning the value does create the variable. However, I also read that it was a good practice to declare it, so I did as you suggested anyway :wink: