Instantly share code, notes, and snippets.

Embed
What would you like to do?
はてなブログの各記事に最終更新日を追加するスクリプト
(function(){
/*
- args: lastmod: str
*/
function addLastmod(lastmod){
/* ここでlastmodを追加 */
var time = document.createElement("time");
time.setAttribute("itemprop", "dateModified");
time.setAttribute("title", lastmod);
time.setAttribute("datetime", lastmod);
time.innerText=lastmod;
var span = document.createElement("span");
span.innerHTML = "(LastModified: " + time.outerHTML + ")";
var date_elements = document.querySelectorAll("div.date")
Array.prototype.map.call(date_elements, function(e){e.appendChild(span);});
}
var blog_uri = document.querySelector("[data-blog-uri]").getAttribute("data-blog-uri");
var sitemap_url = blog_uri + "sitemap.xml";
var article_url = document.querySelector('[property="og:url"]').getAttribute("content");
function fetch2str(res) {
return res.text();
}
function str2dom(str) {
var parser = new DOMParser();
var dom = parser.parseFromString(str, 'text/xml');
return dom;
}
/*
return : Promise([URL1, URL2, ...])
*/
function getSitemapURLArrayPromiseFromSitemapXML() {
return fetch(sitemap_url)
.then(fetch2str)
.then(str2dom)
.then(function(dom) {
return Array.prototype.map.call(dom.querySelectorAll("sitemap"), function(e) {
return e.querySelector("loc").innerHTML
});
});
}
/*
- return Promise([""<xml >?page=1...</xml>", "<xml >?page=2...</xml>", ...])
*/
function getXMLStrArrayPromiseFromAllSitemapURL(URL_array) {
return Promise.all(URL_array.map(function(e) {
return fetch(e).then(fetch2str);
}));
}
/*
return Promise(url_element in DOMParser)
*/
function find_urlElementMatchedAtriclePromiseFromXMLStrArray(xml_str_arr) {
var parser = new DOMParser();
var find_url_e = undefined;
for (var xml_str of xml_str_arr) {
var dom = parser.parseFromString(xml_str, 'text/xml');
var url_elements = dom.querySelectorAll("url");
find_url_e = Array.prototype.find.call(url_elements, function(e, idx, arr) {
return e.querySelector("loc").innerHTML === article_url;
});
if (find_url_e) break;
}
return find_url_e;
}
function getLastmodFrom_urlElement(url_element){
return url_element.querySelector("lastmod").innerHTML;
}
try{
getSitemapURLArrayPromiseFromSitemapXML()
.then(getXMLStrArrayPromiseFromAllSitemapURL)
.then(find_urlElementMatchedAtriclePromiseFromXMLStrArray)
.then(getLastmodFrom_urlElement)
.then(addLastmod);
}catch(e){
console.log(e);
}
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment