/    Sign up×
Community /Pin to ProfileBookmark

Changing canonical

Hi all,

I want to add a canonical to a page that is gerated with my CMS.

For instance, I want to add: <link rel=”canonical” href=”testURL” /> to my page.

I figured that this possibele using Javascript and tried the following:

<head>

<script type=”text/javascript”>
var head = document.getElementsByTagName(‘head’)[0];
var canonical = document.createElement(‘link’);
canonical.setAttribute(‘rel’,’canonical’);
canonical.setAttribute(‘href’,’testurl’);
head.appendChild(canonical);
</script>

</head>

Question: Why doesn’t this work?

I am not experienced in programming in Javascript, but I have some basic skills.

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@Vince616Apr 18.2013 — Hi bud

Your script is working fine, just because you can&#8217;t see it doesn&#8217;t mean that it isn&#8217;t there.
<i>
</i>&lt;script type="text/javascript"&gt;

var head = document.getElementsByTagName('head')[0];
var canonical = document.createElement('link');
canonical.setAttribute('rel','canonical');
canonical.setAttribute('href','testurl');
head.appendChild(canonical);

alert(head.childNodes[head.childNodes.length-1].rel)
&lt;/script&gt;

That said I am a bit confused as to why you would want to do this! Most bots spiders crawlers (whatever you want to call them) do not run javascript, that said the googlebot is rumoured to run scripts and make ajax calls but google itself is rather tight lipped on the subject, but some webmasters have noticed javascript errors in the server logs inferring that the googlebot is running some scripts

Surely your easiest workaround is to just use the canonical link in the way it was intended.
<i>
</i>&lt;link rel="canonical" href="testURL" /&gt;
Copy linkTweet thisAlerts:
@rnd_meApr 18.2013 — static meta like that must by pfysically present in the html server, adding it in js won't do anything because it's only used when the page loads.
×

Success!

Help @superkees spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...