iceshrimp-legacy/packages/client/src/scripts/copy-to-clipboard.ts

34 lines
804 B
TypeScript
Raw Normal View History

/**
* Clipboardに値をコピー(TODO: 文字列以外も対応)
*/
2023-01-13 05:40:33 +01:00
export default (val) => {
2019-01-22 21:20:28 +01:00
// 空div 生成
2023-01-13 05:40:33 +01:00
const tmp = document.createElement("div");
2019-01-22 21:20:28 +01:00
// 選択用のタグ生成
2023-01-13 05:40:33 +01:00
const pre = document.createElement("pre");
2019-01-22 21:20:28 +01:00
// 親要素のCSSで user-select: none だとコピーできないので書き換える
2023-01-13 05:40:33 +01:00
pre.style.webkitUserSelect = "auto";
pre.style.userSelect = "auto";
2019-01-22 21:20:28 +01:00
tmp.appendChild(pre).textContent = val;
// 要素を画面外へ
const s = tmp.style;
2023-01-13 05:40:33 +01:00
s.position = "fixed";
s.right = "200%";
2019-01-22 21:20:28 +01:00
// body に追加
document.body.appendChild(tmp);
// 要素を選択
document.getSelection().selectAllChildren(tmp);
// クリップボードにコピー
2023-01-13 05:40:33 +01:00
const result = document.execCommand("copy");
2019-01-22 21:20:28 +01:00
// 要素削除
document.body.removeChild(tmp);
return result;
};