Is it possible to use JavaScript to change the meta-tags of the page?

JavascriptJqueryMeta Tags

Javascript Problem Overview


If I put a div in the head and display:none, than use JavaScript to display it, will this work?

Edit:

I have stuff loaded in AJAX. And as my AJAX changes the "main" portion of the site, I want to change the meta-tags as well.

Javascript Solutions


Solution 1 - Javascript

Yes, it is.

E.g. to set the meta-description:

document.querySelector('meta[name="description"]').setAttribute("content", _desc);

Solution 2 - Javascript

Yes, you can do that.

There are some interesting use cases: Some browsers and plugins parse meta elements and change their behavior for different values.

Examples

Skype: Switch off phone number parser
<meta name="SKYPE_TOOLBAR" content="SKYPE_TOOLBAR_PARSER_COMPATIBLE">
iPhone: Switch off phone number parser
<meta name="format-detection" content="telephone=no">
Google Chrome Frame
<meta http-equiv="X-UA-Compatible" content="chrome=1">
Viewport definition for mobile devices
<meta name="viewport" content="width=device-width, initial-scale=1.0">

This one can be changed by JavaScript. See: A fix for iPhone viewport scale bug

Meta description

Some user agents (Opera for example) use the description for bookmarks. You can add personalized content here. Example:

<!DOCTYPE html>
<title>Test</title>
<meta name="description" content="this is old">
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.2.js'></script>

<button>Change description</button>

<script type='text/javascript'>
$('button').on('click', function() {
	// Just replacing the value of the 'content' attribute will not work.
	$('meta[name=description]').remove();
	$('head').append( '<meta name="description" content="this is new">' );
});
</script>

So, it’s not just about search engines.

Solution 3 - Javascript

You'd use something like (with jQuery):

$('meta[name=author]').attr('content', 'New Author Name');

But that would be mostly pointless as meta tags are usually only scraped when the document is loaded, usually without executing any JavaScript.

Solution 4 - Javascript

It is definitely possible to use Javascript to change the meta tags of the page. Here is a Javascript only approach:

document.getElementsByTagName('meta')["keywords"].content = "My new page keywords!!";
document.getElementsByTagName('meta')["description"].content = "My new page description!!";
document.title = "My new Document Title!!";

I have verified that Google does index these client side changes for the code above.

Solution 5 - Javascript

You can change meta with, for example, jQuery calls, like this ones:

$('meta[name=keywords]').attr('content', new_keywords);
$('meta[name=description]').attr('content', new_description);

I think it does matter for now, since google said that they will index ajax content via #!hashes and _escaped_fragment_ calls. And now they can verify it (even automatically, with headless browsers, see the 'Creating HTML Snapshots' link on the page mentioned above), so I think it is the way for hardcore SEO guys.

Solution 6 - Javascript

meta-tags are part of the dom and can be accessed and -i guess- changed, but search-engines (the main consumers of meta-tags) won't see the change as the javascript won't be executed. so unless you're changing a meta-tag (refresh comes to mind) which has implications in the browser, this might be of little use?

Solution 7 - Javascript

You can use more simpler and lighter solution:

document.head.querySelector('meta[name="description"]').content = _desc

Solution 8 - Javascript

It should be possible like this (or use jQuery like $('meta[name=author]').attr("content");):

<html>
<head>
<title>Meta Data</title>
<meta name="Author" content="Martin Webb">
<meta name="Author" content="A.N. Other">
<meta name="Description" content="A sample html file for extracting meta data">
<meta name="Keywords" content="JavaScript, DOM, W3C">

</head>

<body>
<script language="JavaScript"><!--
if (document.getElementsByName) {
  var metaArray = document.getElementsByName('Author');
  for (var i=0; i<metaArray.length; i++) {
	document.write(metaArray[i].content + '<br>');
  }

  var metaArray = document.getElementsByName('Description');
  for (var i=0; i<metaArray.length; i++) {
	document.write(metaArray[i].content + '<br>');
  }

  var metaArray = document.getElementsByName('Keywords');
  for (var i=0; i<metaArray.length; i++) {
	document.write(metaArray[i].content + '<br>');
  }
}
//--></script>
</body>

</html>

Solution 9 - Javascript

$(document).ready(function() {
  $('meta[property="og:title"]').remove();
  $('meta[property="og:description"]').remove();
  $('meta[property="og:url"]').remove();
  $("head").append('<meta property="og:title" content="blubb1">');
  $("head").append('<meta property="og:description" content="blubb2">');
  $("head").append('<meta property="og:url" content="blubb3">');
});

Solution 10 - Javascript

var metaTag = document.getElementsByTagName('meta');
for (var i=0; i < metaTag.length; i++) {
    if (metaTag[i].getAttribute("http-equiv")=='refresh')
        metaTag[i].content = '666';
    if (metaTag[i].getAttribute("name")=='Keywords')
        metaTag[i].content = 'js, solver';
}

Solution 11 - Javascript

For anyone trying to change og:title meta tags (or any other). I managed to do it this way:

document.querySelector('meta[property="og:title"]').setAttribute("content", "Example with og title meta tag");

Attention that the 'meta[property="og:title"]' contains the word PROPERTY, and not NAME.

Solution 12 - Javascript

simple add and div atribute to each meta tag example

<meta id="mtlink" name="url" content="">
<meta id="mtdesc" name="description" content="" />
<meta id="mtkwrds" name="keywords" content="" />

now like normal div change for ex. n click

<a href="#" onClick="changeTags(); return false;">Change Meta Tags</a>

function change tags with jQuery

function changeTags(){
   $("#mtlink").attr("content","http://albup.com");
   $("#mtdesc").attr("content","music all the time");
   $("#mtkwrds").attr("content","mp3, download music, ");

}

Solution 13 - Javascript

If we don't have the meta tag at all, then we can use the following:

var _desc = 'Out description';
var meta = document.createElement('meta');
meta.setAttribute('name', 'description');
meta.setAttribute('content', _desc);
document.getElementsByTagName('head')[0].appendChild(meta);

Solution 14 - Javascript

The name attribute allows you to refer to an element by its name (like id) through a list of children, so fast way is:

document.head.children.namedItem('description').content = '...'

— or even just:

document.head.children.description.content = '...'

But if you are not sure if such a meta-tag exists, then it is better to add a check like this:

let metaDescription = document.head.children.description
if (metaDescription == null) {
  metaDescription = document.createElement('meta')
  metaDescription.name = 'description'
  document.head.append(metaDescription)
}
metaDescription.content = '...'

Solution 15 - Javascript

No, a div is a body element, not a head element

EDIT: Then the only thing SEs are going to get is the base HTML, not the ajax modified one.

Solution 16 - Javascript

Yes, it is possible to add metatags with Javascript. I did in my example

https://stackoverflow.com/questions/3604886/android-not-respecting-metatag-removal

But, I dont know how to change it other then removing it. Btw, in my example.. when you click the 'ADD' button it adds the tag and the viewport changes respectively but I dont know how to revert it back (remove it, in Android).. I wish there was firebug for Android so I saw what was happening. Firefox does remove the tag. if anybody has any ideas on this please note so in my question.

Solution 17 - Javascript

var description=document.getElementsByTagName('h4')[0].innerHTML;
var link = document.createElement('meta');
  
link.setAttribute('name', 'description');
  
link.content = description;
  
document.getElementsByTagName('head')[0].appendChild(link);
var htwo=document.getElementsByTagName('h2');
var hthree=document.getElementsByTagName('h3');
var ls=[];
for(var i=0;i<hthree.length;i++){ls.push(htwo[i].innerHTML);}

for(var i=0;i<hthree.length;i++){ls.push(hthree[i].innerHTML);}

var keyword=ls.toString()
;
var keyw = document.createElement('meta');
  
keyw.setAttribute('name', 'keywords');
  
keyw.content = keyword;
  
document.getElementsByTagName('head')[0].appendChild(keyw);

in my case, I write this code and all my meta tags are working perfectly but we can not see the actual meta tag it will be hidden somewhere.

Solution 18 - Javascript

have this in index

<link rel="opengraph" href="{http://yourPage.com/subdomain.php}"/>

have this in ajaxfiles og:type"og:title"og:description and og: image

and add this also

<link rel="origin" href={http://yourPage.com}/>

then add in js after the ajaxCall

FB.XFBML.parse();

Edit: You can then display the correct title and image to facebook in txt/php douments(mine are just named .php as extensions, but are more txt files). I then have the meta tags in these files, and the link back to index in every document, also a meta link in the index file for every subfile..

if anyone knows a better way of doing this I would appreciate any additions :)

Solution 19 - Javascript

This seems to be working for a little rigidly geometrically set app where it needs to run on both mobile and other browsers with little change, so finding the mobile/non-mobile browser status and for mobiles setting the viewport to device-width is needed. As scripts can be run from the header, the below js in header seems to change the metatag for device-width Before the page loads. One might note that the use of navigator.userAgent is stipulated as experimental. The script must follow the metatag entry to be changed, so one must choose some initial content, and then change on some condition.

<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>  
  var userAgentHeader = navigator.userAgent ; 
  var browserIsMobileOrNot = "mobileNOT" ; 
  if( userAgentHeader.includes( "Mobi" ) ) { 
    browserIsMobileOrNot = "mobileYES" ; 
    //document.querySelector('meta[name="viewport"]').setAttribute( "content", "width=device-width, initial-scale=1.0" );
  } else { 
    browserIsMobileOrNot = "mobileNOT" ;  
    document.querySelector('meta[name="viewport"]').setAttribute( "content", "");
  }
</script>

<link rel="stylesheet" href="css/index.css">

. . . . . .

Solution 20 - Javascript

Here is how to do it with plain javascript. I used it to change the header color in the new Safari 15 beta:

<html><head>

	<meta id="themeColor" name="theme-color" content="">

</head><body><script>

	var delay = 50;
	var increment = 5;
	var current = 0 - increment;

	function setHeaderColor(){

		current += increment;
		if (current > 360) current = 0;

		var colorStr = 'hsl('+current+',100%,50%)';
		themeColor.content = colorStr;
		textBlock.style.color = colorStr;
	}

	setInterval(setHeaderColor, delay);

</script><pre id="textBlock" style="font-size:30px;">

  Needs Safari 15

</pre></body></html>

Link to working example: blog.svija.love.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTIMEXView Question on Stackoverflow
Solution 1 - JavascriptjaymsView Answer on Stackoverflow
Solution 2 - JavascriptfuxiaView Answer on Stackoverflow
Solution 3 - JavascriptMiffTheFoxView Answer on Stackoverflow
Solution 4 - JavascriptTimView Answer on Stackoverflow
Solution 5 - JavascripteyedmaxView Answer on Stackoverflow
Solution 6 - JavascriptfutttaView Answer on Stackoverflow
Solution 7 - JavascriptAli SeyfollahiView Answer on Stackoverflow
Solution 8 - JavascriptMikael SvensonView Answer on Stackoverflow
Solution 9 - Javascriptuser3320390View Answer on Stackoverflow
Solution 10 - JavascriptLanPartaczView Answer on Stackoverflow
Solution 11 - JavascriptJorge MauricioView Answer on Stackoverflow
Solution 12 - JavascriptBurhan IbrahimiView Answer on Stackoverflow
Solution 13 - JavascriptRomanView Answer on Stackoverflow
Solution 14 - JavascriptYozhikView Answer on Stackoverflow
Solution 15 - JavascriptBenView Answer on Stackoverflow
Solution 16 - JavascriptChamilyanView Answer on Stackoverflow
Solution 17 - JavascriptSomen DasView Answer on Stackoverflow
Solution 18 - JavascriptsuntoView Answer on Stackoverflow
Solution 19 - Javascriptjcj52436999View Answer on Stackoverflow
Solution 20 - JavascriptAndrew SwiftView Answer on Stackoverflow