コピーイベントまたはペーストイベントのいずれかの結果として送出されるイベントオブジェクトの clipboardData プロパティを使用すると、クリップボードのデータを読み書きできます。
コピーイベントまたはカットイベントの処理時にクリップボードに書き込むには、clipboardData オブジェクトの setData() メソッドを使用し、コピーするデータと MIME タイプを渡します。
function customCopy(event){
event.clipboardData.setData("text/plain", "A copied string.");
}
ペーストされるデータにアクセスするには、clipboardData オブジェクトの getData() メソッドを使用し、データ形式の MIME タイプを渡します。使用できる形式は、types プロパティによって通知されます。
function customPaste(event){
var pastedData = event.clipboardData("text/plain");
}
getData() メソッドと types プロパティには、paste イベントから送出されるイベントオブジェクト内でのみアクセスできます。
次の例では、デフォルトのコピー&ペースト動作を HTML ページでオーバーライドする方法を示します。copy イベントハンドラーは、コピーされるテキストをイタリック体にして、HTML テキストとしてクリップボードにコピーします。cut イベントハンドラーは、選択されたデータをクリップボードにコピーし、ドキュメントからデータを削除します。paste ハンドラーは、クリップボードの内容を HTML として挿入し、さらに挿入部分のスタイルを太字にします。
<html>
<head>
<title>Copy and Paste</title>
<script language="javascript" type="text/javascript">
function onCopy(event){
var selection = window.getSelection();
event.clipboardData.setData("text/html","<i>" + selection + "</i>");
event.preventDefault();
}
function onCut(event){
var selection = window.getSelection();
event.clipboardData.setData("text/html","<i>" + selection + "</i>");
var range = selection.getRangeAt(0);
range.extractContents();
event.preventDefault();
}
function onPaste(event){
var insertion = document.createElement("b");
insertion.innerHTML = event.clipboardData.getData("text/html");
var selection = window.getSelection();
var range = selection.getRangeAt(0);
range.insertNode(insertion);
event.preventDefault();
}
</script>
</head>
<body onCopy="onCopy(event)"
onPaste="onPaste(event)"
onCut="onCut(event)">
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium
doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore
veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam
voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur
magni dolores eos qui ratione voluptatem sequi nesciunt.</p>
</body>
</html>