PHPマニュアルから関数をコピーするボタンを追加するユーザースクリプト


PHPマニュアルから関数を

function(, )

形式でクリップボードにコピーします。

Qiitaのコードにコピーボタンを追加するユーザースクリプト
の使い回しです。

動作確認環境

Windows7 + Firefox41 + Greasemonkey
今回も
Firefoxのスクラッチパッド機能で開発→Greasemonkeyへ貼り付け
なので、Greasemonkey依存は無いはずです。

デモ

コード

copy_function.user.js

copy_function.user.js

// ==UserScript==
// @name        copy function
// @namespace   khsk
// @description 関数説明から関数をコピーするスクリプト
// @include     http://php.net/manual/*/*
// @include     http://www.php.net/manual/*/*
// @include     http://jp.php.net/manual/*/*
// @version     1
// @grant       none
// ==/UserScript==

console.time('Copy function')
delete console.log;
var button = document.createElement('button')
button.innerHTML = 'Copy'
button.addEventListener('click', function(e){
  e.preventDefault() 
  if (!document.queryCommandSupported('copy')) {
    alert('copyに対応していません')
    return
  }
  if (typeof span === "undefined") {
    // グローバルにコピーする要素を作成する
    span = document.createElement('span')
    // 関数名の取得
    var methodName = document.getElementsByClassName('methodname')[0].textContent
    // ,数の取得
    var comma = '';
    var method = document.getElementsByClassName('methodsynopsis dc-description')[0].textContent
    var pos = method.indexOf(",")
    while ( pos != -1 ) {
      comma += ', '
      pos = method.indexOf(",", pos + 1);
    }
    span.innerHTML = methodName + '(' + comma + ')'
    span.id = 'userCopy'
    document.getElementsByTagName('body')[0].appendChild(span)
  }

  // 手動の選択状態を解除する
  window.getSelection().removeAllRanges();
  // コピー対象を選択状態にする
  // 表示されないと選択できないので一時解除
  span.style.display = '';
  var range = document.createRange()
  range.selectNode(span)
  window.getSelection().addRange(range)
  try {
    document.execCommand('copy')
  } catch (e) {
    alert('copyに失敗しました')  
  }
  // 選択を解除する
  window.getSelection().removeAllRanges();
  span.style.display = 'none';
})

document.getElementsByClassName('methodsynopsis dc-description')[0].appendChild(button)

console.timeEnd('Copy function')

課題

  1. オプション引数のカンマを含めるかどうかの設定
  2. 関数が複数書かれている場合の対応
  3. 実行URLの調整

チェックをあまりしていないので対応できていない関数ページも多いと思います。
マニュアルのURL構成が、
http://php.net/manual/*/funciton.*
ではすべてカバーできないみたいなので、一旦
http://php.net/manual/*/*
にしています。
関数ページ以外はエラーで停止している状態だと思います…


直接クリップボードを操作することは難しかったので、目的のテキストを持った要素を新規に追加して、それに対してコピーしました。