JavaScript >> Javascript 文檔 >  >> JavaScript

快速提示:使用 JavaScript 訪問剪貼板

在本文中,我們將向您展示如何使用簡單的原生 JavaScript 片段:

  1. 在用戶操作時將文本添加到剪貼板,例如按下按鈕。
  2. 在用戶複製內容時修改剪貼板的內容。

我們將使用的 API 不需要任何外部庫,並且具有幾乎完美的瀏覽器兼容性!

點擊複製

您可以添加到您的網站的一個很棒的可訪問性功能是能夠通過按鈕直接複製字符串。此交互可用於快速抓取 URL、長字符串(如 SSH 密鑰、終端命令、十六進制顏色)或任何其他經常複製和粘貼的數據。

為了實現這一點,我們需要使用一個很酷的 JavaScript 方法,叫做 execCommand() .它允許我們調用許多不同的事件來操作可編輯的內容,例如使文本變為粗體/斜體、撤消/重做以及復制/剪切/粘貼。

document.execCommand('copy');

這與在鍵盤上按 CTRL/Cmd+C 完全一樣,因此為了複製任何文本,我們首先需要選擇它。這在 JavaScript 中是可能的,這要歸功於 Selection API,它允許我們以編程方式從頁面上的任何 HTML 元素中進行文本選擇。

var button = document.getElementById("copy-button"),
    contentHolder = document.getElementById("content-holder");

button.addEventListener("click", function() {

    // We will need a range object and a selection.
    var range = document.createRange(),
        selection = window.getSelection();

    // Clear selection from any previous data.
    selection.removeAllRanges();

    // Make the range select the entire content of the contentHolder paragraph.
    range.selectNodeContents(contentHolder);

    // Add that range to the selection.
    selection.addRange(range);

    // Copy the selection to clipboard.
    document.execCommand('copy');

    // Clear selection if you want to.
    selection.removeAllRanges();

}, false);

要查看實際示例,請查看下面的編輯器:

var button = document.getElementById("copy-button"),
    contentHolder = document.getElementById("content-holder");

button.addEventListener("click", function() {

    // We will need a range object and a selection.
    var range = document.createRange(),
        selection = window.getSelection();

    // Clear selection from any previous data.
    selection.removeAllRanges();

    // Make the range select the entire content of the contentHolder paragraph.
    range.selectNodeContents(contentHolder);

    // Add that range to the selection.
    selection.addRange(range);

    // Copy the selection to clipboard.
    document.execCommand('copy');

    // Clear selection if you want to.
    selection.removeAllRanges();

}, false);
<p id="content-holder">This text will be inserted into the clipboard.</p>

<button id="copy-button">Copy Text</button>

<textarea placeholder="Paste here"></textarea>
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body{
    padding: 20px;
    font: normal 16px sans-serif;
    color: #555;
}

p{
    margin-bottom: 20px;
}

button{
    padding: 8px 12px;
    margin-bottom: 20px;
}

textarea {
    display: block;
    padding: 10px;
    width: 400px;
    height: 120px;
}

在上面的示例中,我們要復制的內容只是存儲在一個段落中。如果您需要的文本不在頁面上,您需要先將其寫入屏幕外隱藏的元素中。

修改複製文本

在這裡,我們將向您展示如何在剪貼板中的內容被複製後進行操作。這對於轉義代碼、格式化數字和日期或其他文本轉換(如大寫、小寫等)非常有用。

JavaScript 為我們提供了 copy()paste() 事件,但它們的設計方式使得存儲在剪貼板中的內容是安全的:

  • 副本中 事件處理程序我們無法讀取剪貼板中存儲的內容,因為可能存在我們不應該訪問的個人信息。但是,我們可以覆蓋剪貼板數據。
  • 粘貼 情況恰恰相反:我們可以讀取數據,但無法更改數據。

由於我們想同時讀取和寫入,我們將需要再次使用 Selection API。這是解決方案:

document.addEventListener('copy', function(e){

    // We need to prevent the default copy functionality,
    // otherwise it would just copy the selection as usual.
    e.preventDefault();

    // The copy event doesn't give us access to the clipboard data,
    // so we need to get the user selection via the Selection API.
    var selection = window.getSelection().toString();

    // Transform the selection in any way we want.
    // In this example we will escape HTML code.
    var escaped = escapeHTML(selection);

    // Place the transformed text in the clipboard. 
    e.clipboardData.setData('text/plain', escaped);

});

您可以在下面的編輯器中嘗試代碼:

document.addEventListener('copy', function(e){

    // We need to prevent the default copy functionality,
    // otherwise it would just copy the selection as usual.
    e.preventDefault();

    // The copy event doesn't give us access to the clipboard data,
    // so we need to get the user selection via the Selection API.
    var selection = window.getSelection().toString();

    // Transform the selection in any way we want.
    var escaped = escapeHtml(selection);

    // Place the transformed text in the clipboard. 
    e.clipboardData.setData('text/plain', escaped);

});

// Primitive HTML escape function.
function escapeHtml(unsafe) {
    return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
 }

<p class="copy-text">Copy and paste any of the HTML code below to escape it.</p>

<pre><code>
&lt;div class=&quot;container&quot;&gt;

    &lt;div class=&quot;starter-template&quot;&gt;
        &lt;h1&gt;Lorem Ipsum&lt;/h1&gt;
        &lt;p class=&quot;lead&quot;&gt;Lorem ipsum dolor sit amet.&lt;/p&gt;
    &lt;/div&gt;

&lt;/div&gt;
</code></pre>

<textarea class="paste-text" placeholder="Paste here"></textarea>
*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body{
    padding: 20px;
    font: normal 16px sans-serif;
    color: #555;
}

pre{
    font-size: 14px;
    margin-bottom: 20px;
}

textarea {
    padding: 10px;
    width: 500px;
    height: 170px;
}

進一步閱讀

在這個快速提示中,我們向您展示了兩個有用的片段,用於在純原生 JavaScript 中使用剪貼板。我們使用了一堆時髦的原生 API,所以如果您想了解更多關於它們的信息,它們又在這裡了:

  • execCommand - 執行複制、粘貼、剪切、粗體、斜體、下劃線、刪除等操作。 - MDN,我可以使用嗎
  • Selection API - 允許開發人員從頁面上的任何文本中進行範圍選擇。 - MDN,我可以使用嗎
  • JavaScript 複製事件 - 當用戶按下 CTRL/Cmd+C 或從右鍵菜單中選擇“複製”時觸發的事件。 - MDN,我可以使用嗎

此外,如果您需要對複制/粘貼/剪切事件進行更多控制,您可以使用諸如 clipobard.js 之類的庫。它有很多功能,並提供了一個很好的干淨的 API 來管理剪貼板。

我們希望您喜歡這篇文章!隨時在下面的評論部分提出問題或留下建議:)


Tutorial JavaScript 教程
  1. 作為 HypeMail 的前端開發人員分配給我的任務。

  2. Flashback - MongoDB Atlas 黑客松提交 |哇哦! 🎉

  3. React 中翻頁效果的最佳庫是什麼?

  4. 使用 SVG 創建一個 13KB 的 JS 遊戲

  5. 我們將一起走的路

  6. 使用 React Javascript(Form-Onsubmit 和調用 API 無法正常工作)

  7. 將 Google 翻譯添加到網站

  1. Cookie、localStorage 還是 sessionStorage?

  2. 如何在 React 中製作一個簡單的滑塊組件

  3. 設置 DaisyUI、Tailwind、Vue 和 Vite

  4. 帶有中等邊框底部的標題 - Bootstrap

  5. 編寫 Javascript 程序的最佳 IDE 是什麼?

  6. 基準測試 JavaScript 循環和方法(第 1 部分)

  7. 使用 React、MongoDB、ExpressJS 和 NodeJS 構建 Todo 應用程序第 2 部分(前端)

  1. 基於命令行的 Web 組合!

  2. 使用 Web 組件創建博客或文檔

  3. 命令行應用程序:使用 puppeteer 抓取 dev.to

  4. 反應路由器 Dom v6