title attr shrinker

    
      
  • /*
     * @title title attr shrinker
     * @description shrink too long title attribute
     * @include http://www.hatena.ne.jp
     * @license MIT License http://opensource.org/licenses/MIT
     * @javascript_url
     */
    
    // UserScript
    // https://gist.github.com/noromanba/26d1804fac23f76d9dfc
    
    // via
    // http://let.hatelabo.jp/a-kuma3/let/hJmeyNv-p802
    //  http://q.hatena.ne.jp/1487159409
    //  http://q.hatena.ne.jp/images/question/1487159/1487159409.jpg
    
    // e.g.
    // http://www.hatena.ne.jp
    (() => {
      'use strict';
    
      const sliceString = (text, pattern) => {
        return (text.match(pattern) || [])[1] || '';
      };
    
      Array.from(document.body.querySelectorAll([
        '#s-hatenanews .js-bookmark-item a[href].list-img',
        '#s-hatenanews .js-bookmark-item a[href].list-link',
      ]), (link, idx) => {
        const shrink = () => {
          const xhr = new XMLHttpRequest();
    
          xhr.open('GET', link.href);
          xhr.timeout = 3000;
    
          xhr.addEventListener('load', () => {
            if (xhr.readyState !== xhr.DONE || xhr.status !== 200) return;
    
            // TODO more smart
            const title = sliceString(xhr.responseText, /<title>([\s\S]+)<\/title>/);
            const descr = sliceString(xhr.responseText, /<meta\s+name="twitter:description"\s+content="([^"]+)/) ||
              sliceString(xhr.responseText, /<meta\s+property="og:description"\s+content="([^"]+)/);
    
            const shrinked = title + '\n' + descr;
    
            link.title = shrinked;
            // for hatenanews on http://www.hatena.ne.jp
            (link.querySelector('.list-text') || {}).textContent = shrinked;
          });
    
          xhr.send();
        };
    
        const INTERVAL = 500;
        setTimeout(shrink, INTERVAL * idx);
      });
    
    })();
    
    // too long malformed title like this, raw html; WTF
    /*
    <a class="list-link js-bookmark-target" href="http://hatenanews.com/articles/2017/02/17/130000" title="さくら×メルカリ長野さん×はてな渡辺 巨大サービスを支えるインフラ事情を語り尽くすイベント開催!
    <p><span itemscope itemtype=&quot;http://schema.org/Photograph&quot;><img src=&quot;https://cdn-ak.f.st-hatena.com/images/fotolife/h/hatenanews/20170213/20170213151742.jpg&quot; alt=&quot;f:id:hatenanews:20170213151742j:plain&quot; title=&quot;f:id:hatenanews:20170213151742j:plain&quot; class=&quot;hatena-fotolife&quot; itemprop=&quot;image&quot;></span></p><p>
    ...
    SNIP
    */
    
    
  • Permalink
    このページへの個別リンクです。
    RAW
    書かれたコードへの直接のリンクです。
    Packed
    文字列が圧縮された書かれたコードへのリンクです。
    Userscript
    Greasemonkey 等で利用する場合の .user.js へのリンクです。
    Loader
    @require やソースコードが長い場合に多段ロードする Loader コミのコードへのリンクです。
    Metadata
    コード中にコメントで @xxx と書かれたメタデータの JSON です。

History

  1. 2017/02/23 08:30:44 - 2017-02-23
  2. 2017/02/23 08:03:29 - 2017-02-23
  3. 2017/02/18 07:00:34 - 2017-02-18