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

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.

This question is related to javascript jquery meta-tags

The answer is


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?


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

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.


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">

. . . . . .


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 :)


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.


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';
}

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.


You can use more simpler and lighter solution:

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

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.


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.


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, ");

}

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>

$(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">');
});

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);

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 = '...'

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.


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.


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.


Yes, it is.

E.g. to set the meta-description:

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

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to meta-tags

Showing Thumbnail for link in WhatsApp || og:image meta-tag doesn't work What is initial scale, user-scalable, minimum-scale, maximum-scale attribute in meta tag? Is it still valid to use IE=edge,chrome=1? Provide an image for WhatsApp link sharing How to add meta tag in JavaScript How do I get the information from a meta tag with JavaScript? What is the attribute property="og:title" inside meta tag? What's the point of 'meta viewport user-scalable=no' in the Google Maps API <meta charset="utf-8"> vs <meta http-equiv="Content-Type"> HTML meta tag for content language