JavaScript can access the web site page meta data through the window document values. Two approaches are taken for the title and the other meta elements.
In the example function below the values of the title and description are copied into two DIVs called Headline and Summary respectively.
In the short example webpage the function showMetaData is used to illustrate the retrieval of the meta data from the web page.
<html>
<head>
<title>Accessing Metadata with JavaScript</title>
<meta name="Keywords" content="JavaScript, Access, Metadata, title, Description, keywords">
<meta name="Description" content="Details about using JavaScript to access the web page's description, keywords and title metadata.">
</head>
<body>
<div id="metaTitle"></div>
<div id="metaDescription"></div>
<div id="metaKeywords"></div>
<script>
function showMetaData() {
document.getElementById("metaTitle").innerHTML=window.document.title;
var m = document.getElementsByTagName('meta');
for(var i=0;i<m.length;i++){
if(m[i].getAttribute('name').toLowerCase() == 'description'){
document.getElementById("metaDescription").innerHTML=m[i].getAttribute('content');
}
if(m[i].getAttribute('name').toLowerCase() == 'keywords'){
document.getElementById("metaKeywords").innerHTML=m[i].getAttribute('content');
}
}
}
showMetaData();
</script>
</body>
</html>
Above the script are the three DIVs which will be populated with the meta data values of the title, description and keywords. This is done to illustrate that the values have been retrieved.
The HTML title is handled differently to other meta tags. Within the function this is considered first in its unique way.
As can be seen the function has a for loop, used to step through each of the meta tags on the page.
In the function, as shown, there are two lines which are picking out meta values for the keywords and descriptions. These illustrate the getting of the meta value and the assignment to the content of the relevant DIV.


