在博客园的博客文章中自动播放插入的 asciinema

需求

我的文章中都是用 Markdown 写的,所以嵌入的 asciinema 只能通过 Embed image link 的方式,这就导致打开文章页面后只有一个 asciinema 的预览图,点击图片后会跳转到 asciinema 网页。我希望不需要跳转,而是直接可以在文章页面播放 asciinema。也就是希望可以 Embed the player,问题是文章页面中不能直接插入 js 代码


最终效果

asciicast


解决方案

  • 首先需要申请博客园的 js 权限
  • 然后在「页脚 HTML 代码」中插入以下代码:

<script type="text/javascript">
// asciinema embedded player
(function() {
  function insertAfter(referenceNode, newNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
  }

  function insertPlayer(link) {
    if (link.href.endsWith('.js')) {
      return;
    }
    var asciicastId = link.href.substring('https://asciinema.org/a/'.length);
    var s = document.createElement('script');
    s.src = link.href + '.js';
    s.id = 'asciicast-' + asciicastId;
    s.async = 'true';
    insertAfter(link, s);
    link.remove();
  }

  window.onload = e=>{
    // var scripts = document.querySelectorAll("script[id^='asciicast-']");
    var scripts = document.querySelectorAll("a[href^='https://asciinema.org/a/']");
    [].forEach.call(scripts, insertPlayer);

    let observer = new MutationObserver(
      mutations=>mutations.forEach(
        m=>[...m.addedNodes]
          .filter(n=>n.tagName=='a')
          .filter(n=>n.href.startsWith('https://asciinema.org/a/'))
          .forEach(insertPlayer)
      )
    );
    observer.observe(document.querySelector('#divCommentShow'), {subtree: true, childList: true});
  }
  
})();
</script>

原理

页面加载完成后,自动插入 asciinema player,并隐藏原来的图片


EOF

posted on 2022-09-01 16:12  明天有风吹  阅读(123)  评论(1)    收藏  举报

导航

+V atob('d2h5X251bGw=')

请备注:from博客园