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

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


Yes, it is.

E.g. to set the meta-description:

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


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.


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.