Replace existing canonical tag with javascript or jquery

北慕城南 提交于 2019-12-10 16:38:58

问题


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>

回答1:


$('link[rel="canonical"]').attr('href', 'NEW_HREF_GOES_HERE');



回答2:


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.



来源:https://stackoverflow.com/questions/29067810/replace-existing-canonical-tag-with-javascript-or-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!