Last active
April 8, 2022 15:14
-
-
Save joeyguerra/7740007 to your computer and use it in GitHub Desktop.
Schema.org microdata parser in Javascript for the client side.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(win){ | |
/* | |
Copied from https://github.com/foolip/microdatajs/blob/master/jquery.microdata.json.js | |
without jQuery. | |
*/ | |
var Schema = (function(doc){ | |
function getTypes(node){ | |
var type = node.getAttribute('itemtype'); | |
if(!type) return []; | |
return type.split(' '); | |
} | |
function getValue(node){ | |
if(node.getAttribute('itemprop') === null) return null; | |
switch(node.tagName.toLowerCase()){ | |
case 'meta': | |
return node.getAttribute('content') || ''; | |
case 'audio': | |
case 'embed': | |
case 'iframe': | |
case 'img': | |
case 'source': | |
case 'track': | |
case 'video': | |
return node.getAttribute('src'); | |
case 'a': | |
case 'area': | |
case 'link': | |
return node.getAttribute('href'); | |
case 'object': | |
return node.getAttribute('data'); | |
case 'data': | |
return node.getAttribute('value') || ''; | |
case 'time': | |
return node.getAttribute('datetime'); | |
default: | |
return node.innerHTML; | |
} | |
} | |
return { | |
toObject: function(node, memory){ | |
var result = {properties: {}}; | |
result.type = getTypes(node); | |
var itemid = node.getAttribute('itemid'); | |
if(itemid) result.id = itemid; | |
var properties = node.querySelectorAll('[itemprop]'); | |
for(var i = 0; i < properties.length; i++){ | |
var value = null; | |
var item = properties[i]; | |
var key = item.getAttribute('itemprop'); | |
if(item.getAttribute('itemscope') !== null){ | |
if(memory.indexOf(item) !== -1){ | |
value = 'ERROR'; | |
}else{ | |
memory.push(item); | |
value = this.toObject(item, memory); | |
memory.pop(); | |
} | |
}else{ | |
value = getValue(item); | |
} | |
result.properties[key] = value; | |
} | |
return result; | |
} | |
, scopes: function(nodes){ | |
if(!nodes) nodes = doc.querySelectorAll('[itemscope]:not([itemprop])'); | |
var scopes = []; | |
for(var i = 0; i < nodes.length; i++){ | |
var scope = nodes[i]; | |
scopes.push(this.toObject(scope, [])); | |
} | |
return scopes; | |
} | |
}; | |
})(win.document); | |
win.Schema = Schema; | |
}(window); |
Yeah, good catch. Would probably require a different design for the scopes
function.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Doesn't work with nested scopes:
The article name is detected as
Skyfall
, notSome article name
.