TITLE:JavaScriptでpreタグで囲まれたソースコードをtextareaにコピーする

Posted by aterai at 2012-07-25

JavaScriptでpreタグで囲まれたソースコードをtextareaにコピーする

概要

以下、Opera 12.50で、Clipboard API を使い、preタグで囲まれたソースコードを簡単にコピーする方法のテスト。

ソースコード

// ==UserScript==
// @name        <pre> to <textarea>
// @namespace   http://terai.xrea.jp/
// @include     http://*
// @exclude     http://*.google.*
// @description pre <-> textarea
// @version     1.0.4
// ==/UserScript==
// Double Click <PRE>, open <TEXTAREA>
// Test: Clipboard API and events

// Fork of <pre> to <textarea> http://userscripts.org/scripts/show/11438
// original author is Sybian http://d.hatena.ne.jp/Sybian/

// _@name        <pre> to <textarea>
// _@namespace   http://d.hatena.ne.jp/Sybian/
// _@include     http://*
// _@description pre <-> textarea
// _@version     1.0.2
// Ctrl+Click <PRE>, become <TEXTAREA>
// ESC or Ctrl+[ or Ctrl+Shift+Click in <TEXTAREA>, restore <PRE>

(function() {
  var listener = function(e) {
    var tx = document.createElement("textarea"),
        div = document.createElement("div"),
    closeListener = function(e) {
      switch(e.type) {
      case 'copy':
      case 'cut':
        var dataTransfer = e.clipboardData;
        dataTransfer.items.add(this.innerText, 'text/plain');
        this.parentNode.replaceChild(this.originalPre, this);
        e.preventDefault();
        break;
      }
    };

    tx.style.width  = parseInt(getComputedStyle(this,"").width).toString()+"px";
    tx.style.height = "240px";
    tx.originalPre  = this;

// ctrl-c 無しでコピーできるかもと思ったけど…
//       var event = new ClipboardEvent('copy', { bubbles: true, cancelable: true } );
//       var dataTransfer = event.clipboardData;
//       dataTransfer.items.add("aaaaaaaaaaaaaaaaaaaaaaa", "text/plain");
//       //this.parentNode.replaceChild(this.originalPre, this);
//       document.dispatchEvent(event);
//       //event.preventDefault();

    tx.addEventListener("keydown", function(e) {
      if(e.keyCode=="27") { // ESC
        this.parentNode.replaceChild(this.originalPre, this);
      }
    }, false);
    tx.addEventListener("dblclick", function(e) {
      this.parentNode.replaceChild(this.originalPre, this);
    }, false);
    div.innerHTML = this.innerHTML.replace(/<br[ \/]*>/ig, "\n").replace(/<.*?>/mg, "");
    tx.value = div.childNodes[0].nodeValue.replace(/\xA0/g, ' ');
    this.tx = tx;
    this.parentNode.replaceChild(this.tx, this);
    this.tx.focus();
    this.tx.select();

    tx.addEventListener('copy', closeListener, false);
    tx.addEventListener('cut',  closeListener, false);
  },
  pre = document.getElementsByTagName("pre"),
  i = 0, len = pre.length;
  for(; i<len; i++) {
    pre[i].addEventListener("dblclick", listener, false);
  }
}());

Bookmarklet版

  • 名前
    • pre2textarea
  • アドレス(YUI Compressor で圧縮)
    javascript:(function(){var d=document.getElementsByTagName("pre"),b=0,a=d.length,c=function(g){var f=document.createElement("textarea"),h=document.createElement("div");f.style.width=parseInt(getComputedStyle(this,"").width).toString()+"px";f.style.height="240px";f.originalPre=this;f.addEventListener("keydown",function(i){if(i.keyCode=="27"){this.parentNode.replaceChild(this.originalPre,this)}},false);f.addEventListener("dblclick",function(i){this.parentNode.replaceChild(this.originalPre,this)},false);h.innerHTML=this.innerHTML.replace(/<br[ \/]*>/ig,"\n").replace(/<.*?>/mg,"");f.value=h.childNodes[0].nodeValue.replace(/\xA0/g," ");this.tx=f;this.parentNode.replaceChild(this.tx,this);this.tx.focus();this.tx.select()};for(;b<a;b++){d[b].addEventListener("dblclick",c,false)}}());

メモ: ローカルにドロップして保存(ファイル名付き)

function makeDraggableDownloadLink(text, mimeType, fileName) {
  var blob = new Blob([text], {type: mimeType}),
         a = document.createElement('a');
  a.appendChild(document.createTextNode("download"));
  if(window.createObjectURL) {
    a.href = window.createObjectURL(blob);
  }else if(window.createBlobURL) {
    a.href = window.createBlobURL(blob);
  }else if(window.webkitURL.createObjectURL) {
    a.href = window.webkitURL.createObjectURL(blob);
  }
  a.addEventListener("dragstart", function(e) {
    e.dataTransfer.setData("DownloadURL", [mimeType,fileName,this.href].join(':'));
  }, false);
  return a;
}

参考リンク

コメント