博客2021年最终功能更新

我对博客功能的要求是拒绝花里胡哨,一切为阅读服务。现在是2021年年底,正好我要为我对年终总结的一些设想给博客更新一些功能:快速引用素材、Steam游戏卡片、引用Wikipedia条目。

快速引用素材

之前我引用图片一直都是用图片的完整路径,实在是非常麻烦,所以我一直期待能找到一个简单的方法引用素材。原先的考虑是用hexo-asset,但是在一番简单搜索后发现hexo-render-marked在3.1.0+已经携带了类似功能了:https://hexo.io/docs/asset-folders.html#Embedding-an-image-using-markdown 。直接在_config.yml里打开就行。

post_asset_folder: true
marked:
  prependRoot: true
  postAsset: true

测试用的可爱Mastodon

Steam游戏卡片

搜刮到hexo-tag-steamgames可以实现这个。

引用Wikipedia条目

Wikipedia is a free-content online encyclopedia written and maintained by a community of volunteers, known as Wikipedians, through open collaboration and the wiki software MediaWiki. Founded by Jimmy Wales and Larry Sanger on January 15, 2001, Wikipedia has been hosted since 2003 by the Wikimedia Foundation, an American nonprofit organization funded mainly by donations from readers. Wikipedia is the largest and most-read reference work in history.

Wikipedia:Wikipedia

原来我是想用hexo-tag-wikipedia。但是:

  1. 这个插件用的不是新的Restful API,实际获取到的字符串千奇百怪。
  2. 这东西一开始用不了,我一看控制台发现一串$.getJSON:它插入的脚本用的JQuery的API。然而我的网页上并没有JQuery。

最后我改了一下把它改成用XMLHTTPRequest从Wikipedia的Restful API拉取数据。脚本很简单:


function buildArgsHash(args) {
    let argsHash = {};
    args.forEach(arg => {
        const params = arg.split(':');
        argsHash[params[0]] = params[1];
    });

    return argsHash;
}

function generateWikipediaTagHtml(args, content) {
    const argsHash = buildArgsHash(args);
    const title = argsHash['title'];

    const lang = argsHash['lang'] !== undefined ? argsHash['lang'] : 'en';
    const baseUrl = `https://${lang}.wikipedia.org`;

    const url = `${baseUrl}/api/rest_v1/page/summary/${title}?redirect=false`;

    const tagId = Math.round(Math.random() * 100000);
    const embeddedScript = `
      window.addEventListener('load', function() {
        var element = document.getElementById('${tagId}');
        var req = new XMLHttpRequest();
        req.addEventListener("load", function() {
          var result = this.response;
          const extract = result.extract;
          element.prepend(extract);
        });
        req.addEventListener("error", function() {
          element.prepend('Failed to fetch wikipedia data for "${title}".');
        });
        req.open('GET', '${url}');
        req.responseType = 'json';
        req.setRequestHeader('accept', 'application/json; charset=utf-8; profile="https://www.mediawiki.org/wiki/Specs/Summary/1.4.2"');
        req.send();
      });
    `;
    let contentText = `<script>${embeddedScript}</script>`;
    if (argsHash['wikiButton'] === 'true') {
        contentText += `<p><a href="${baseUrl}/wiki/${title}">Wikipedia:${title}</a></p>`;
    }

    return `<blockquote id='${tagId}'>${contentText}</blockquote>`;
}

hexo.extend.tag.register('wikipedia', generateWikipediaTagHtml);

我把它塞到了我的fork里( https://github.com/thislight/hexo-tag-wikipedia ),找时间我可能问问作者再把它合并到上游,因为有一个breaking change。我打算后面把它改成在服务器上获取,这样动态插入一大段文字的体验挺糟糕,而且每一个访客都要获取一次有点滥用资源的意思。