javascript 将文本写入剪贴板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13899299/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:06:13  来源:igfitidea点击:

Write text to Clipboard

javascriptgoogle-chrome-extensionclipboard

提问by David Brisker

I want to write some text variable into clipboard via Chrome Extension, it will be happened when user presses a short-key. I've done all parts except writing to clipboard.

我想通过 Chrome 扩展将一些文本变量写入剪贴板,当用户按下快捷键时会发生这种情况。除了写入剪贴板之外,我已经完成了所有部分。

I've searched entire StackOverflow using these keywords: "[google-chrome-extension] Clipboard"

我使用这些关键字搜索了整个 StackOverflow:“[google-chrome-extension] 剪贴板”

So I want to say, I've seen all related to:

所以我想说,我看过所有相关的:

  • Add clipboardReadand clipboardWritepermission (already done)
  • Add text into a <textarea>, call document.execCommand('Copy');or document.execCommand("Copy", false, null);
  • 添加clipboardReadclipboardWrite权限(已完成)
  • 将文本添加到<textarea>, call document.execCommand('Copy');document.execCommand("Copy", false, null);

Even I tried my extension on StackOverflow's textareaand I inserted my text into wmd-input part of StackOverflow textarea, then selected it, then called copy. Nothing, nothing, nothing...

甚至我在 StackOverflow 上尝试了我的扩展textarea并将我的文本插入到 StackOverflow 的wmd-input 部分textarea,然后选择它,然后调用复制。没什么,没什么,没什么……

Everything tried. Please advise... What am I missing?

一切都试过了。请指教...我错过了什么?

采纳答案by Sudarshan

You can try the following code, it writes text to clipboard

您可以尝试以下代码,它将文本写入剪贴板

As an example i wrote Sampleto clipboard

作为一个例子,我写到Sample剪贴板

Output

输出

enter image description here

在此处输入图片说明

manifest.json

清单文件.json

manifest file is key for all chrome extensions, ensured it is with all permissions

manifest 文件是所有 chrome 扩展的关键,确保它具有所有权限

 {
  "name": "Copy to ClipBoard Demo",
  "description" : "This is used for demonstrating Copy to Clip Board Functionality",
  "version": "1",
  "browser_action": {
    "default_popup": "popup.html"
  },
  "permissions":["clipboardWrite"],
    "manifest_version": 2
}

popup.html

弹出窗口.html

A trivial Browser action HTML File, with input box and button

一个简单的浏览器操作 HTML 文件,带有输入框和按钮

<html>

    <head>
        <script src="popup.js"></script>
    </head>

    <body>
        <input type="text" id="text" placeHolder="Enter Text To Copy"></input>
        <button id="copy">Copy</button>
    </body>

</html>

popup.js

弹出窗口.js

It copies content in <input>to clipboard

它将内容复制<input>到剪贴板

function copy() {

    //Get Input Element
    var copyDiv = document.getElementById('text');

    //Give the text element focus
    copyDiv.focus();

    //Select all content
    document.execCommand('SelectAll');

    //Copy Content
    document.execCommand("Copy", false, null);
}

//Add Event Listeners to Button Click
document.addEventListener("DOMContentLoaded", function () {
    document.getElementById("copy").onclick = copy;
});

OR

或者

function copy(){

    //Get Input Element
    document.getElementById("text").select();

    //Copy Content
    document.execCommand("Copy", false, null);
}

//Add Event Listeners to Button Click
document.addEventListener("DOMContentLoaded", function () {
    document.getElementById("copy").onclick = copy;
});

回答by user2573802

Based on https://stackoverflow.com/a/12693636

基于https://stackoverflow.com/a/12693636

function directCopy(str){
    //based on https://stackoverflow.com/a/12693636
        document.oncopy = function(event) {
    event.clipboardData.setData("Text", str);
    event.preventDefault();
        };
    document.execCommand("Copy");
        document.oncopy = undefined;
}

回答by SethWhite

Suonds like you're trying to copy from a content script. Building off joelptand Jeff Gran's answers from this answer, here's how to copy any piece of text from a content script:

就像您试图从内容脚本中复制一样。从这个答案中构建joelptJeff Gran的答案,以下是从内容脚本中复制任何文本的方法:

"permissions": [
    "clipboardWrite",...
"permissions": [
    "clipboardWrite",...

In your main.js or any background script:

在您的 main.js 或任何后台脚本中:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse){
  var copyFrom = document.createElement("textarea");
  copyFrom.textContent = request.text;
  var body = document.getElementsByTagName('body')[0];
  body.appendChild(copyFrom);
  copyFrom.select();
  document.execCommand('copy');
  body.removeChild(copyFrom);
})

From your content script:

从您的内容脚本:

chrome.runtime.sendMessage({text:textToCopy});

回答by Petr Varyagin

Usage example:

用法示例:

copyStringToClipboard("abc123");

copyStringToClipboard("abc123");

    function copyStringToClipboard (str) {
      // Create new element
      var el = document.createElement('textarea');
      // Set value (string to be copied)
      el.value = str;
      // Set non-editable to avoid focus and move outside of view
      el.setAttribute('readonly', '');
      el.style = {position: 'absolute', left: '-9999px'};
      document.body.appendChild(el);
      // Select text inside element
      el.select();
      // Copy text to clipboard
      document.execCommand('copy');
      // Remove temporary element
      document.body.removeChild(el);
    }