閑古鳥

オールドプログラマの日記。プログラミングとか病気(透析)の話とか。

JavaScriptで任意の文字列をクリップボードにコピーしたい(Chrome)

document.execCommand('copy') でブラウザで選択している文字列をコピーできるらしい。

任意の文字列を含む要素をでっち上げて一時的に選択してあげれば良いのかな?

var r = document.createRange();
var text = document.createTextNode("コピーしたい文字列");
r.selectNode(document.body.appendChild(text)); // body直下に突っ込んで
window.getSelection().addRange(r); // 選択して
document.execCommand('copy'); // コピー
text.remove(); // お役御免

雑だけど自分用ツール内ではこれでいいかな…。