LoginSignup
2
2

More than 5 years have passed since last update.

Qiitaの記事ページで目次をコンテンツエリアにも表示するユーザースクリプト

Last updated at Posted at 2016-09-16

動機

Qiitaには記事内容の見出しから目次をページ内リンクとして表示する機能があります。

ところがその目次、投稿ユーザーの「人気の投稿」や広告エリアの下に表示されるので、ある程度スクロールしなければ内容を確認できず、記事の中身を見る前に概要や規模をざっくり把握するのには使えません。

そこで、右側に表示される目次をコピーしてコンテンツエリア上部に表示するユーザースクリプトを作りました。

インストール

ユーザースクリプト拡張をインストール後、
Chrome: Tampermonkey
Firefox: Greasemonkey

下記URLのRawボタンから。
https://gist.github.com/mino0123/17b0b1ef8c323baeb9e41219ab95f311

イメージ


スクリーンショット 2016-09-16 0.06.41.png


ソースコード

// ==UserScript==
// @name        Qiita_TOC_to_content
// @namespace   mino0123
// @include     http://qiita.com/*/items/*
// @include     http://qiita.com/*/private/*
// @version     1
// @grant       none
// ==/UserScript==

const subColumnEl = document.getElementsByClassName('col-sm-3')[0];

if (subColumnEl) {

  const observer = new MutationObserver((mutations) => {

    const tocTreeEl = document.getElementsByClassName('tocTree')[0];
    const contentEl = document.querySelector('.markdownContent.clearfix');// avoid slide
    const hasTocItem = tocTreeEl.getElementsByTagName('li').length > 0;

    if (tocTreeEl && contentEl && hasTocItem) {
      // Disconnect observer
      observer.disconnect();
      // Copy toc to content
      const cloneToc = tocTreeEl.cloneNode(true);
      cloneToc.className += ' tocToContent';
      contentEl.insertBefore(cloneToc, contentEl.firstChild);
      // Add styles
      const styleEl = document.createElement('style');
      styleEl.type = 'text/css';
      styleEl.innerHTML = `
                          .tocToContent {
                            width: 100% !important;
                            border: 1px solid #CCC;
                            font-size: 70%;
                          }
                          .tocToContent a {
                            display: inline !important;
                          }
                          `;
      document.head.appendChild(styleEl);
    }

  });

  observer.observe(subColumnEl, { childList: true, subtree: true });

}
  • 2016/11/25 Qiitaの更新に伴って動かなくなっていたので修正
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2