4040

テキストをクリップボードにコピーする最良の方法は何ですか (マルチブラウザ)?

私が試してみました:

function copyToClipboard(text) {
    if (window.clipboardData) { // Internet Explorer
        window.clipboardData.setData("Text", text);
    } else {
        unsafeWindow.netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
        const clipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"].getService(Components.interfaces.nsIClipboardHelper);
        clipboardHelper.copyString(text);
    }
}

しかし、Internet Explorer では構文エラーが発生します。Firefox ではunsafeWindow is not defined と表示されます。

Flashを使用しない便利なトリック: Trello はユーザーのクリップボードにどのようにアクセスしますか?

4

67 に答える 67

3006

概要

クリップボードにコピーするための主要なブラウザー API は 3 つあります。

  1. 非同期クリップボード API [navigator.clipboard.writeText]

    • Chrome 66 (2018 年 3 月)で利用可能なテキスト中心の部分
    • アクセスは非同期で、JavaScript Promisesを使用します。セキュリティ ユーザー プロンプト (表示される場合) がページ内の JavaScript を中断しないように記述できます。
    • テキストは、変数から直接クリップボードにコピーできます。
    • HTTPS 経由で提供されるページでのみサポートされます。
    • Chrome 66 ページでは、非アクティブなタブは、権限を求めるプロンプトなしでクリップボードに書き込むことができます。
  2. document.execCommand('copy')(非推奨)

    • 2015 年 4 月までの時点で、ほとんどのブラウザーがこれをサポートしています (下記のブラウザー サポートを参照してください)。
    • アクセスは同期的です。つまり、セキュリティ プロンプトの表示やユーザー操作が完了するまで、ページ内の JavaScript を停止します。
    • テキストは DOM から読み取られ、クリップボードに配置されます。
    • 2015 年 4 月までのテスト中、クリップボードへの書き込み中に許可プロンプトが表示されるのは Internet Explorer のみでした。
  3. コピー イベントのオーバーライド

    • コピー イベントのオーバーライドに関するクリップボード API ドキュメントを参照してください。
    • コピー イベントからクリップボードに表示される内容を変更できます。プレーン テキスト以外の他の形式のデータを含めることができます。
    • 質問への直接的な回答ではないため、ここでは説明しません。

一般的な開発ノート

コンソールでコードをテストしている間は、クリップボード関連のコマンドが機能するとは思わないでください。一般に、ページはアクティブ (Async Clipboard API) である必要があるかdocument.execCommand('copy')、クリップボードへのアクセス ( ) を許可するユーザー インタラクション (ユーザー クリックなど) が必要です。詳細については、以下を参照してください。

重要(ここに記載 2020/02/20)

この投稿は当初、クロスオリジンIFRAMEおよびその他のIFRAME の "サンドボックス化" でのアクセス許可の非推奨が書かれたものであるため、埋め込まれたデモの "コード スニペットの実行" ボタンと "codepen.io の例" が一部のブラウザー (Chrome や Microsoft Edge を含む) で機能しないことに注意してください。 )。

開発するには、独自の Web ページを作成し、HTTPS 接続を介してそのページを提供して、テストおよび開発を行います。

コードの動作を示すテスト/デモページは次のとおりです: https://deanmarktaylor.github.io/clipboard-test/

非同期 + フォールバック

新しい Async Clipboard API に対するブラウザー サポートのレベルが原因で、document.execCommand('copy')適切なブラウザー カバレッジを得るためにメソッドにフォールバックすることをお勧めします。

簡単な例を次に示します (このサイトに埋め込んでも機能しない場合があります。上記の「重要な」注意事項をお読みください):

function fallbackCopyTextToClipboard(text) {
  var textArea = document.createElement("textarea");
  textArea.value = text;
  
  // Avoid scrolling to bottom
  textArea.style.top = "0";
  textArea.style.left = "0";
  textArea.style.position = "fixed";

  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Fallback: Copying text command was ' + msg);
  } catch (err) {
    console.error('Fallback: Oops, unable to copy', err);
  }

  document.body.removeChild(textArea);
}
function copyTextToClipboard(text) {
  if (!navigator.clipboard) {
    fallbackCopyTextToClipboard(text);
    return;
  }
  navigator.clipboard.writeText(text).then(function() {
    console.log('Async: Copying to clipboard was successful!');
  }, function(err) {
    console.error('Async: Could not copy text: ', err);
  });
}

var copyBobBtn = document.querySelector('.js-copy-bob-btn'),
  copyJaneBtn = document.querySelector('.js-copy-jane-btn');

copyBobBtn.addEventListener('click', function(event) {
  copyTextToClipboard('Bob');
});


copyJaneBtn.addEventListener('click', function(event) {
  copyTextToClipboard('Jane');
});
<div style="display:inline-block; vertical-align:top;">
  <button class="js-copy-bob-btn">Set clipboard to BOB</button><br /><br />
  <button class="js-copy-jane-btn">Set clipboard to JANE</button>
</div>
<div style="display:inline-block;">
  <textarea class="js-test-textarea" cols="35" rows="4">Try pasting into here to see what you have on your clipboard:

  </textarea>
</div>

(codepen.io の例は機能しない可能性があります。上記の「重要な」注意事項をお読みください) このスニペットは Stack Overflow の埋め込みプレビューではうまく機能しないことに注意してください: https://codepen.io/DeanMarkTaylor/pen/RMRaJX?editors =1011

非同期クリップボード API

Chrome 66 のアクセス許可 API を介して「アクセス許可をリクエスト」し、クリップボードへのアクセスをテストする機能があることに注意してください。

var text = "Example text to appear on clipboard";
navigator.clipboard.writeText(text).then(function() {
  console.log('Async: Copying to clipboard was successful!');
}, function(err) {
  console.error('Async: Could not copy text: ', err);
});

document.execCommand('コピー')

この投稿の残りの部分では、document.execCommand('copy')API のニュアンスと詳細について説明します。

ブラウザのサポート

JavaScript のdocument.execCommand('copy')サポートが強化されました。ブラウザーの更新については、以下のリンクを参照してください。 (非推奨)

簡単な例

(このサイトに埋め込まれても機能しない場合があります。上記の「重要な」注意事項をお読みください)

var copyTextareaBtn = document.querySelector('.js-textareacopybtn');

copyTextareaBtn.addEventListener('click', function(event) {
  var copyTextarea = document.querySelector('.js-copytextarea');
  copyTextarea.focus();
  copyTextarea.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copying text command was ' + msg);
  } catch (err) {
    console.log('Oops, unable to copy');
  }
});
<p>
  <button class="js-textareacopybtn" style="vertical-align:top;">Copy Textarea</button>
  <textarea class="js-copytextarea">Hello I'm some text</textarea>
</p>

複雑な例: 入力を表示せずにクリップボードにコピー

上記の単純な例は、textareaまたはinput要素が画面に表示されている場合にうまく機能します。

場合によっては、input/textarea要素を表示せずにテキストをクリップボードにコピーしたいことがあります。これは、これを回避する方法の 1 つの例です (基本的に、要素を挿入し、クリップボードにコピーし、要素を削除します)。

Google Chrome 44、Firefox 42.0a1、および Internet Explorer 11.0.8600.17814 でテスト済み。

(このサイトに埋め込まれても機能しない場合があります。上記の「重要な」注意事項をお読みください)

function copyTextToClipboard(text) {
  var textArea = document.createElement("textarea");

  //
  // *** This styling is an extra step which is likely not required. ***
  //
  // Why is it here? To ensure:
  // 1. the element is able to have focus and selection.
  // 2. if the element was to flash render it has minimal visual impact.
  // 3. less flakyness with selection and copying which **might** occur if
  //    the textarea element is not visible.
  //
  // The likelihood is the element won't even render, not even a
  // flash, so some of these are just precautions. However in
  // Internet Explorer the element is visible whilst the popup
  // box asking the user for permission for the web page to
  // copy to the clipboard.
  //

  // Place in the top-left corner of screen regardless of scroll position.
  textArea.style.position = 'fixed';
  textArea.style.top = 0;
  textArea.style.left = 0;

  // Ensure it has a small width and height. Setting to 1px / 1em
  // doesn't work as this gives a negative w/h on some browsers.
  textArea.style.width = '2em';
  textArea.style.height = '2em';

  // We don't need padding, reducing the size if it does flash render.
  textArea.style.padding = 0;

  // Clean up any borders.
  textArea.style.border = 'none';
  textArea.style.outline = 'none';
  textArea.style.boxShadow = 'none';

  // Avoid flash of the white box if rendered for any reason.
  textArea.style.background = 'transparent';


  textArea.value = text;

  document.body.appendChild(textArea);
  textArea.focus();
  textArea.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copying text command was ' + msg);
  } catch (err) {
    console.log('Oops, unable to copy');
  }

  document.body.removeChild(textArea);
}


var copyBobBtn = document.querySelector('.js-copy-bob-btn'),
  copyJaneBtn = document.querySelector('.js-copy-jane-btn');

copyBobBtn.addEventListener('click', function(event) {
  copyTextToClipboard('Bob');
});


copyJaneBtn.addEventListener('click', function(event) {
  copyTextToClipboard('Jane');
});
<div style="display:inline-block; vertical-align:top;">
  <button class="js-copy-bob-btn">Set clipboard to BOB</button><br /><br />
  <button class="js-copy-jane-btn">Set clipboard to JANE</button>
</div>
<div style="display:inline-block;">
  <textarea class="js-test-textarea" cols="35" rows="4">Try pasting into here to see what you have on your clipboard:

  </textarea>
</div>

その他の注意事項

ユーザーがアクションを実行した場合にのみ機能します

すべてのdocument.execCommand('copy')呼び出しは、クリック イベント ハンドラなどのユーザー アクションの直接の結果として発生する必要があります。これは、予期しないときにユーザーのクリップボードをいじるのを防ぐための措置です。

詳細については、こちらの Google Developers の投稿を参照してください。

クリップボード API

完全な Clipboard API ドラフト仕様は、 https ://w3c.github.io/clipboard-apis/ にあります。

サポートされていますか?

  • document.queryCommandSupported('copy')trueコマンドが「ブラウザでサポートされている」場合に返されます。
  • 今呼び出された場合に成功する場合はdocument.queryCommandEnabled('copy')戻ります。コマンドがユーザーが開始したスレッドから呼び出されたこと、およびその他の要件が満たされていることを確認します。truedocument.execCommand('copy')

ただし、ブラウザーの互換性の問題の例として、2015 年 4 月から 10 月までの Google Chrome は、ユーザーが開始したスレッドからコマンドが呼び出された場合にのみ返さtrueれました。document.queryCommandSupported('copy')

以下の互換性の詳細に注意してください。

ブラウザの互換性の詳細

ユーザーのクリックの結果として呼び出される/ブロックdocument.execCommand('copy')でラップされた単純な呼び出しは、最も互換性のある使用法を取得しますが、以下にはいくつかの条件があります。trycatch

document.execCommanddocument.queryCommandSupportedまたはへの呼び出しは、 /ブロックdocument.queryCommandEnabledでラップする必要があります。trycatch

ブラウザの実装とブラウザのバージョンが異なると、 を返す代わりに呼び出されたときに、異なるタイプの例外がスローされますfalse

さまざまなブラウザーの実装はまだ流動的であり、Clipboard APIはまだドラフト段階であるため、忘れずにテストを行ってください。

于 2015-06-12T18:56:18.323 に答える
1335

クリップボードへの自動コピーは危険な場合があるため、ほとんどのブラウザー (Internet Explorer を除く) では非常に困難です。個人的には、次の簡単なトリックを使用します。

function copyToClipboard(text) {
  window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
}

ユーザーには、コピーするテキストが既に選択されているプロンプト ボックスが表示されます。Ctrl+CEnter(ボックスを閉じる)を押すだけで十分です。

これで、クリップボードのコピー操作は安全になりました。これは、ユーザーが手動で行うためです (ただし、非常に簡単な方法です)。もちろん、すべてのブラウザで動作します。

<button id="demo" onclick="copyToClipboard(document.getElementById('demo').innerHTML)">This is what I want to copy</button>

<script>
  function copyToClipboard(text) {
    window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
  }
</script>

于 2011-05-19T08:06:06.560 に答える
93

Web ページからクリップボードを読み取ったり変更したりすると、セキュリティとプライバシーの問題が発生します。ただし、Internet Explorer では可能です。このスニペットの例を見つけました:

    <script type="text/javascript">
        function select_all(obj) {
            var text_val=eval(obj);
            text_val.focus();
            text_val.select();
            r = text_val.createTextRange();
            if (!r.execCommand) return; // feature detection
            r.execCommand('copy');
        }
    </script>
    <input value="http://www.sajithmr.com"
     onclick="select_all(this)" name="url" type="text" />

于 2008-12-30T13:33:45.303 に答える
88

非常にシンプルなソリューション (統合に 5 分もかからない) が必要で、箱から出してすぐに見栄えがする場合は、 Clippyがより複雑なソリューションの優れた代替手段になります。

GitHub の共同創設者によって書かれました。以下の Flash 埋め込みコードの例:

<object
    classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
    width="110"
    height="14"
    id="clippy">

    <param name="movie" value="/flash/clippy.swf"/>
    <param name="allowScriptAccess" value="always"/>
    <param name="quality" value="high"/>
    <param name="scale" value="noscale"/>
    <param NAME="FlashVars" value="text=#{text}"/>
    <param name="bgcolor" value="#{bgcolor}"/>
    <embed
        src="/flash/clippy.swf"
        width="110"
        height="14"
        name="clippy"
        quality="high"
        allowScriptAccess="always"
        type="application/x-shockwave-flash"
        pluginspage="http://www.macromedia.com/go/getflashplayer"
        FlashVars="text=#{text}"
        bgcolor="#{bgcolor}"/>
</object>

#{text}コピーする必要があるテキストと#{bgcolor}色で置き換えることを忘れないでください。

于 2010-10-17T14:40:35.000 に答える
77

私は最近、まさにこの問題について技術的なブログ投稿を書きました (私は Lucidchart で働いており、最近クリップボードのオーバーホールを行いました)。

Ctrlプレーン テキストをクリップボードにコピーするのは、システム コピー イベント (ユーザーが+を押すCか、ブラウザーのメニューを使用)中に行おうとすると、比較的簡単です。

var isIe = (navigator.userAgent.toLowerCase().indexOf("msie")    != -1 ||
            navigator.userAgent.toLowerCase().indexOf("trident") != -1);

document.addEventListener('copy', function(e) {
    var textToPutOnClipboard = "This is some text";
    if (isIe) {
        window.clipboardData.setData('Text', textToPutOnClipboard);
    } else {
        e.clipboardData.setData('text/plain', textToPutOnClipboard);
    }
    e.preventDefault();
});

システム コピー イベント以外でテキストをクリップボードに書き込むのは、はるかに困難です。これらの他の回答のいくつかは、Flashを介してそれを行う方法を参照しているように見えます.Flashは、それを行う唯一のクロスブラウザの方法です(私が理解している限り)。

それ以外にも、ブラウザごとにいくつかのオプションがあります。

これは Internet Explorer で最も単純で、次の方法で JavaScript からいつでも clipboardData オブジェクトにアクセスできます。

window.clipboardData

(ただし、システムの切り取り、コピー、または貼り付けイベントの外部でこれを行おうとすると、Internet Explorer はユーザーに Web アプリケーションのクリップボードのアクセス許可を付与するように求めます。)

Chrome では、クリップボードのアクセス許可を付与する Chrome 拡張機能を作成できます(これは、Lucidchart で行っていることです)。次に、拡張機能がインストールされているユーザーの場合は、システム イベントを自分で発生させる必要があります。

document.execCommand('copy');

Firefox には、ユーザーが特定のサイトにクリップボードへのアクセス許可を付与できるオプションがいくつかあるようですが、個人的には試していません。

于 2014-12-03T20:31:06.940 に答える
73

私はこれが好きです:

<input onclick="this.select();" type='text' value='copy me' />

ユーザーが OS でテキストをコピーする方法を知らない場合、貼り付けの方法も知らない可能性があります。したがって、それを自動的に選択するだけで、残りはユーザーに任せることができます。

于 2013-04-23T22:32:03.287 に答える
58

clipboard.jsは、テキストまたは HTML データをクリップボードにコピーできる小さな非 Flash ユーティリティです。使い方はとても簡単で、.js をインクルードして次のように使用するだけです。

<button id='markup-copy'>Copy Button</button>

<script>
document.getElementById('markup-copy').addEventListener('click', function() {
  clipboard.copy({
    'text/plain': 'Markup text. Paste me into a rich text editor.',
    'text/html': '<i>here</i> is some <b>rich text</b>'
  }).then(
    function(){console.log('success'); },
    function(err){console.log('failure', err);
  });

});
</script>

clipboard.js もGitHubにあります。

注:これは現在非推奨です。ここに移行します

于 2015-08-11T15:33:37.223 に答える
29

Chrome 42+ と Firefox 41+ はdocument.execCommand('copy')コマンドをサポートするようになったので、 Tim Down の古い回答Google Developer の回答を組み合わせて使用​​して、クロスブラウザーのクリップボードへのコピー機能用の関数をいくつか作成しました。:

function selectElementContents(el) {
    // Copy textarea, pre, div, etc.
    if (document.body.createTextRange) {
        // Internet Explorer
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.select();
        textRange.execCommand("Copy");
    }
    else if (window.getSelection && document.createRange) {
        // Non-Internet Explorer
        var range = document.createRange();
        range.selectNodeContents(el);
        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
        try {
            var successful = document.execCommand('copy');
            var msg = successful ? 'successful' : 'unsuccessful';
            console.log('Copy command was ' + msg);
        }
        catch (err) {
            console.log('Oops, unable to copy');
        }
    }
} // end function selectElementContents(el)

function make_copy_button(el) {
    var copy_btn = document.createElement('input');
    copy_btn.type = "button";
    el.parentNode.insertBefore(copy_btn, el.nextSibling);
    copy_btn.onclick = function() {
        selectElementContents(el);
    };

    if (document.queryCommandSupported("copy") || parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2]) >= 42) {
        // Copy works with Internet Explorer 4+, Chrome 42+, Firefox 41+, Opera 29+
        copy_btn.value = "Copy to Clipboard";
    }
    else {
        // Select only for Safari and older Chrome, Firefox and Opera
        copy_btn.value = "Select All (then press Ctrl + C to Copy)";
    }
}
/* Note: document.queryCommandSupported("copy") should return "true" on browsers that support copy,
    but there was a bug in Chrome versions 42 to 47 that makes it return "false".  So in those
    versions of Chrome feature detection does not work!
    See https://code.google.com/p/chromium/issues/detail?id=476508
*/

make_copy_button(document.getElementById("markup"));
<pre id="markup">
  Text that can be copied or selected with cross browser support.
</pre>

于 2015-11-05T03:50:33.120 に答える
27

私が取り組んできたプロジェクトの 1 つである、ZeroClipboardライブラリを利用する jQuery クリップボードへのコピー プラグインです。

jQuery のヘビー ユーザーであれば、ネイティブの Zero Clipboard プラグインよりも簡単に使用できます。

于 2011-05-03T22:17:01.680 に答える
25

私は次の解決策を見つけました:

キーダウンハンドラーは「pre」タグを作成します。このタグにコピーするコンテンツを設定してから、このタグを選択して、ハンドラーでtrueを返します。これにより、Chromeの標準ハンドラーが呼び出され、選択したテキストがコピーされます。

また、必要に応じて、前の選択を復元する関数のタイムアウトを設定できます。MooToolsでの私の実装:

function EnybyClipboard() {
    this.saveSelection = false;
    this.callback = false;
    this.pastedText = false;

    this.restoreSelection = function() {
        if (this.saveSelection) {
            window.getSelection().removeAllRanges();
            for (var i = 0; i < this.saveSelection.length; i++) {
                window.getSelection().addRange(this.saveSelection[i]);
            }
            this.saveSelection = false;
        }
    };

    this.copyText = function(text) {
        var div = $('special_copy');
        if (!div) {
            div = new Element('pre', {
                'id': 'special_copy',
                'style': 'opacity: 0;position: absolute;top: -10000px;right: 0;'
            });
            div.injectInside(document.body);
        }
        div.set('text', text);
        if (document.createRange) {
            var rng = document.createRange();
            rng.selectNodeContents(div);
            this.saveSelection = [];
            var selection = window.getSelection();
            for (var i = 0; i < selection.rangeCount; i++) {
                this.saveSelection[i] = selection.getRangeAt(i);
            }
            window.getSelection().removeAllRanges();
            window.getSelection().addRange(rng);
            setTimeout(this.restoreSelection.bind(this), 100);
        } else return alert('Copy did not work. :(');
    };

    this.getPastedText = function() {
        if (!this.pastedText) alert('Nothing to paste. :(');
        return this.pastedText;
    };

    this.pasteText = function(callback) {
        var div = $('special_paste');
        if (!div) {
            div = new Element('textarea', {
                'id': 'special_paste',
                'style': 'opacity: 0;position: absolute;top: -10000px;right: 0;'
            });
            div.injectInside(document.body);
            div.addEvent('keyup', function() {
                if (this.callback) {
                    this.pastedText = $('special_paste').get('value');
                    this.callback.call(null, this.pastedText);
                    this.callback = false;
                    this.pastedText = false;
                    setTimeout(this.restoreSelection.bind(this), 100);
                }
            }.bind(this));
        }
        div.set('value', '');
        if (document.createRange) {
            var rng = document.createRange();
            rng.selectNodeContents(div);
            this.saveSelection = [];
            var selection = window.getSelection();
            for (var i = 0; i < selection.rangeCount; i++) {
                this.saveSelection[i] = selection.getRangeAt(i);
            }
            window.getSelection().removeAllRanges();
            window.getSelection().addRange(rng);
            div.focus();
            this.callback = callback;
        } else return alert('Failed to paste. :(');
    };
}

使用法:

enyby_clip = new EnybyClipboard(); // Init

enyby_clip.copyText('some_text'); // Place this in the Ctrl+C handler and return true;

enyby_clip.pasteText(function callback(pasted_text) {
    alert(pasted_text);
}); // Place this in Ctrl+V handler and return true;

貼り付けると、テキストエリアが作成され、同じように機能します。

PS:たぶん、このソリューションは、Flashなしで完全なクロスブラウザーソリューションを作成するために使用できます。FirefoxとChromeで動作します。

于 2012-07-05T15:33:32.850 に答える
24

他の方法では、プレーンテキストをクリップボードにコピーします。HTMLをコピーするには(つまり、結果をWYSIWYGエディターに貼り付けることができます)、InternetExplorerでのみ次の操作を実行できます。ブラウザが実際にコンテンツを視覚的に選択するため、これは他の方法とは根本的に異なります。

// Create an editable DIV and append the HTML content you want copied
var editableDiv = document.createElement("div");
with (editableDiv) {
    contentEditable = true;
}
editableDiv.appendChild(someContentElement);

// Select the editable content and copy it to the clipboard
var r = document.body.createTextRange();
r.moveToElementText(editableDiv);
r.select();
r.execCommand("Copy");

// Deselect, so the browser doesn't leave the element visibly selected
r.moveToElementText(someHiddenDiv);
r.select();
于 2008-12-30T14:33:38.287 に答える
14

Flash 10 の時点では、アクションが Flash オブジェクトとのユーザー インタラクションから発生した場合にのみ、クリップボードにコピーできます。( Adobe の Flash 10 発表の関連セクションを参照してください。)

解決策は、[コピー] ボタンの上に Flash オブジェクトをオーバーレイするか、コピーを開始する任意の要素をオーバーレイすることです。ZeroClipboard は、現在、この実装に最適なライブラリです。経験豊富な Flash 開発者は、独自のライブラリを作成したいだけかもしれません。

于 2010-03-17T20:12:39.990 に答える
13

すでに多くの回答がありますが、追加したい(jQuery)。どのブラウザでも、モバイルブラウザでもうまく機能します(つまり、セキュリティに関するプロンプトが表示されますが、それを受け入れるとうまく機能します).

function appCopyToClipBoard(sText)
{
    var oText = false,
        bResult = false;
    try
    {
        oText = document.createElement("textarea");
        $(oText).addClass('clipboardCopier').val(sText).insertAfter('body').focus();
        oText.select();
        document.execCommand("Copy");
        bResult = true;
    }
    catch(e) {
    }

    $(oText).remove();
    return bResult;
}

あなたのコードで:

if (!appCopyToClipBoard('Hai there! This is copied to the clipboard.'))
{
    alert('Sorry, copy to clipboard failed.');
}
于 2016-12-12T16:22:02.410 に答える
10

カスタム グリッド編集 (Excel など) の作成と Excel との互換性について、同じ問題がありました。複数のセルの選択、コピーと貼り付けをサポートする必要がありました。

解決策:ユーザーがコピーするデータを挿入するテキストエリアを作成し(ユーザーがセルを選択しているとき)、それにフォーカスを設定し(たとえば、ユーザーが を押したときCtrl)、テキスト全体を選択します。

したがって、ユーザーがCtrl+Cを押すと、選択したセルがコピーされます。テキストエリアのサイズを 1 ピクセルに変更するだけでテストした後 (display:none で動作するかどうかはテストしませんでした)。すべてのブラウザで問題なく動作し、ユーザーに対して透過的です。

貼り付け - このように同じことを行うことができます (ターゲットによって異なります) - テキストエリアに焦点を合わせ、onpaste を使用して貼り付けイベントをキャッチします (私のプロジェクトでは、セル内のテキストエリアを使用して編集します)。

例 (商用プロジェクト) を貼り付けることはできませんが、アイデアはわかります。

于 2011-01-17T17:09:45.453 に答える
10

これは、他の回答との組み合わせです。

var copyToClipboard = function(textToCopy){
    $("body")
        .append($('<textarea name="fname" class="textToCopyInput"/>' )
        .val(textToCopy))
        .find(".textToCopyInput")
        .select();
      try {
        var successful = document.execCommand('copy');
        var msg = successful ? 'successful' : 'unsuccessful';
        alert('Text copied to clipboard!');
      } catch (err) {
          window.prompt("To copy the text to clipboard: Ctrl+C, Enter", textToCopy);
      }
     $(".textToCopyInput").remove();
}

jQuery を使用していますが、もちろんそうである必要はありません。必要に応じて変更できます。jQueryを自由に使えるようになりました。CSS を追加して、入力が表示されないようにすることもできます。たとえば、次のようなものです。

.textToCopyInput{opacity: 0; position: absolute;}

またはもちろん、インライン スタイリングを行うこともできます。

.append($('<textarea name="fname" style="opacity: 0;  position: absolute;" class="textToCopyInput"/>' )
于 2015-07-09T14:24:25.117 に答える
10

Internet Explorer 以外のブラウザーでは、小さな Flash オブジェクトを使用してクリップボードを操作する必要があります。

于 2008-12-30T13:38:51.957 に答える
8

これはChase Seibert's answer の拡張であり、Internet Explorer 9 の DIV だけでなく、IMAGE および TABLE 要素に対しても機能するという利点があります。

if (document.createRange) {
    // Internet Explorer 9 and modern browsers
    var r = document.createRange();
    r.setStartBefore(to_copy);
    r.setEndAfter(to_copy);
    r.selectNode(to_copy);
    var sel = window.getSelection();
    sel.addRange(r);
    document.execCommand('Copy');  // Does nothing on Firefox
} else {
    // Internet Explorer 8 and earlier. This stuff won't work
    // on Internet Explorer 9.
    // (unless forced into a backward compatibility mode,
    // or selecting plain divs, not img or table).
    var r = document.body.createTextRange();
    r.moveToElementText(to_copy);
    r.select()
    r.execCommand('Copy');
}
于 2011-08-12T08:17:32.383 に答える
8

私はclipboard.jsを使用しました。

npm で取得できます。

npm install clipboard --save

バウアーでも

bower install clipboard --save

new ClipboardJS("#btn1");

document.querySelector("#btn2").addEventListener("click", () => document.querySelector("#btn1").dataset.clipboardText = Math.random());
<script src="https://cdn.jsdelivr.net/npm/clipboard@2.0.8/dist/clipboard.min.js"></script>

<button id="btn1" data-clipboard-text="Text to copy goes here">
    Copy to clipboard
</button>
<button id="btn2">Click here to change data-clipboard-text</button>

<br /><br />

<input type="text" placeholder="Paste here to see clipboard" />

その他の使用法と例はhttps://zenorocha.github.io/clipboard.js/にあります。

于 2015-10-28T11:17:06.240 に答える
6

質問を読み間違えたようですが、参考までに、DOMの範囲を抽出し(クリップボードではなく、最新のすべてのブラウザーと互換性があります)、oncopy、onpaste、およびonbeforepasteイベントと組み合わせてクリップボードの動作を取得できます。これを実現するためのコードは次のとおりです。

function clipBoard(sCommand) {
  var oRange = contentDocument.createRange();
  oRange.setStart(startNode, startOffset);
  oRange.setEnd(endNode, endOffset);

  /* This is where the actual selection happens.
     in the above, startNode and endNode are
     DOM nodes defining the beginning and
     end of the "selection" respectively.

     startOffset and endOffset are constants
     that are defined as follows:

         END_TO_END: 2
         END_TO_START: 3
         NODE_AFTER: 1
         NODE_BEFORE: 0
         NODE_BEFORE_AND_AFTER: 2
         NODE_INSIDE: 3
         START_TO_END: 1
         START_TO_START: 0

     And it would be used like oRange.START_TO_END
  */

  switch(sCommand) {

    case "cut":
      this.oFragment = oRange.extractContents();
      oRange.collapse();
      break;

    case "copy":
      this.oFragment = oRange.cloneContents();
      break;

    case "paste":
      oRange.deleteContents();
      var cloneFragment = this.oFragment.cloneNode(true)
      oRange.insertNode(cloneFragment);
      oRange.collapse();
      break;
  }
}
于 2011-08-16T19:22:47.043 に答える
6

JavaScript/TypeScript でこのコマンドを使用する最良かつ簡単な方法

navigator.clipboard.writeText(textExample);

textExampleでクリップボードにコピーしたい値を渡すだけです

于 2022-01-29T13:45:39.867 に答える
5

Greasemonkey\JavaScript Copy to Clipboard ボタンまたはこのスニペットの元のソースからコードを取得したようです...

このコードは Greasemonkey 用であったため、unsafeWindow です。constまた、Internet Explorer の構文エラーは、Firefox 固有のキーワード (に置き換えてください) に由来するものと思われvarます。

于 2008-12-30T14:47:36.013 に答える
5

これは、インターネット中のさまざまな方法を調べた後、私がこれまでに取り組んできた唯一のものでした. これは厄介なトピックです。世界中で多くの解決策が投稿されていますが、それらのほとんどは機能しませ。これは私のために働いた:

注: このコードは、「onClick」メソッドなどへの直接同期コードとして実行された場合にのみ機能します。Ajax への非同期応答またはその他の非同期の方法で呼び出すと、機能しません。

copyToClipboard(text) {
    var copyText = document.createElement("input");
    copyText.type = "text";
    document.body.appendChild(copyText);
    copyText.style = "display: inline; width: 1px;";
    copyText.value = text;
    copyText.focus();
    document.execCommand("SelectAll");
    document.execCommand("Copy");
    copyText.remove();
}

私は、このコードが 1 ピクセル幅のコンポーネントを画面上に 1 ミリ秒間表示することを理解していますが、それについては心配しないことにしました。

于 2017-10-14T23:15:10.663 に答える
5

私の知る限り、それは Internet Explorer でのみ機能します。

Dynamic Tools - JavaScript Copy To Clipboardも参照してください。ただし、ユーザーは最初に構成を変更する必要があり、それでも機能しないようです。

于 2008-12-30T13:26:42.183 に答える
4

入力ボックス以外のテキスト (任意の div/span タグ内のテキスト) をページからコピーする必要があり、次のコードを思い付きました。唯一の秘訣は、非表示フィールドを TEXT 型にすることです。タイプが非表示の場合は機能しません。

function copyToClipboard(sID) {
    var aField = document.getElementById("hiddenField");

    aField.hidden = false;
    aField.value  = document.getElementById(sID).textContent;
    aField.select();
    document.execCommand("copy");
    alert("Following text has been copied to the clipboard.\n\n" + aField.value);
    aField.hidden = true;
}

そして、HTML に以下を追加します。

input type="text" id="hiddenField" style="width:5px;border:0" />
...
于 2017-01-09T02:22:17.233 に答える
3

「clipboardRead」パーミッションが許可されている Chrome 拡張機能でクリップボードからテキストを読み取る場合は、次のコードを使用できます。

function readTextFromClipboardInChromeExtension() {
    var ta = $('<textarea/>');
    $('body').append(ta);
    ta.focus();
    document.execCommand('paste');
    var text = ta.val();
    ta.blur();
    ta.remove();
    return text;
}
于 2013-10-21T11:39:39.470 に答える
3

document.execCommandUpdate 2015: 現在、クリップボードを操作する方法があります。

clipboard.jsは、クロスブラウザーでクリップボードを操作する方法を提供します (ブラウザーのサポート)。

于 2015-10-05T09:29:10.970 に答える
2

私は clipboard.js を使用するつもりでしたが、(まだ) モバイル ソリューションが用意されていないので、非常に小さなライブラリを作成しました。

シュヴァル

これにより、テキストがコピーされるか (デスクトップ、Android、および Safari 10 以降)、少なくともテキストが選択されます (iOS の古いバージョン)。縮小すると、1 kB 強になります。デスクトップ Safari (バージョン 10 より前) では、ユーザーに"Press Command + C to copy"と指示します。また、使用するために JavaScript を記述する必要もありません。

于 2015-10-10T04:13:00.630 に答える
2

Chrome では、 を使用できますcopy('the text or variable etc')。これはクロスブラウザーではありませんが (スニペットでは機能しませんか? )、他のクロスブラウザーの回答に追加できます。

于 2014-07-02T14:28:28.423 に答える
2

すべてのケースをカバーする単純なソリューションでいくつかの関数をコンパイルし、必要に応じて迅速なフォールバックを行いました。

window.copyToClipboard = function(text) {
  // Internet Explorer specific
  if (window.clipboardData && window.clipboardData.setData) {
    return clipboardData.setData("Text", text);
  }

  // All other modern browsers
  target = document.createElement("textarea");
  target.style.position = "absolute";
  target.style.left = "-9999px";
  target.style.top = "0";
  target.textContent = text;
  document.body.appendChild(target);
  target.focus();
  target.setSelectionRange(0, target.value.length);

  // Copy the selection of fall back to prompt
  try {
    document.execCommand("copy");
    target.remove();
    console.log('Copied to clipboard: "'+text+'"');
  }
  catch(e) {
    console.log("Can't copy string on this browser. Try to use Chrome, Firefox or Opera.")
    window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
  }
}

ここでテストしてください: https://jsfiddle.net/jv0avz65/

于 2017-07-13T11:16:47.820 に答える
2

JavaScript 機能を使用try/catchすると、次のようにエラー処理を改善することもできます。

copyToClipboard() {
    let el = document.getElementById('Test').innerText
    el.focus(); // el.select();
    try {
        var successful = document.execCommand('copy');
        if (successful) {
            console.log('Copied Successfully! Do whatever you want next');
        }
        else {
            throw ('Unable to copy');
        }
    }
    catch (err) {
        console.warn('Oops, Something went wrong ', err);
    }
}
于 2018-01-19T16:30:29.043 に答える
1

セキュリティ上の理由から、それを行うことはできません。クリップボードにコピーするには、Flash を選択する必要があります。

これをお勧めします:http://zeroclipboard.org/

于 2015-05-07T12:36:18.500 に答える
1

Safariやその他のブラウザ(Internet Explorer 9以降)に対応したソリューションを探したところ、

GitHub と同じものを使用します: ZeroClipboard

例:

http://zeroclipboard.org/index-v1.x.html

HTML

<html>
  <body>
    <button id="copy-button" data-clipboard-text="Copy Me!" title="Click to copy me.">Copy to Clipboard</button>
    <script src="ZeroClipboard.js"></script>
    <script src="main.js"></script>
  </body>
</html>

JavaScript

var client = new ZeroClipboard(document.getElementById("copy-button"));

client.on("ready", function (readyEvent) {
    // alert( "ZeroClipboard SWF is ready!" );

    client.on("aftercopy", function (event) {
        // `this` === `client`
        // `event.target` === the element that was clicked
        event.target.style.display = "none";
        alert("Copied text to clipboard: " + event.data["text/plain"]);
    });
});
于 2016-05-25T15:06:19.373 に答える