【问题标题】:javascript copy with execCommand使用 execCommand 进行 javascript 复制
【发布时间】:2017-11-22 16:50:58
【问题描述】:

我想从 html 元素的数据集中复制一些内容。

HTML 代码

<p id="web-password-@{{ id }}" data-password="@{{ password }}" 
data-state="0">@{{ hidePassword }}</p>

<button class="mdl-button mdl-js-button mdl-button--icon">

    <i data-event="copy" data-obj="util" data-target="web-password-@{{ id }}" 
    class="material-icons clickable-icon">content_copy</i>

</button>

复制方法

通过 data-event 和 data-obj 属性调用该方法。

copy (args) {

    let copyText = document.getElementById(args.target).dataset.password;

    console.log(copyTest); // output: specific password

    document.execCommand("Copy");
}

这样它不会将内容复制到剪贴板。有人看到错误了吗?

更新

以下代码适用于 html 元素的实际 textContent。

但我需要从 data-password 属性中复制值

let range = document.createRange();

let selection = window.getSelection();

let node = document.getElementById(args.target);

range.selectNodeContents(node);

selection.removeAllRanges();

selection.addRange(range);

document.execCommand("copy");

可能的解决方案

所以我将值写入隐藏输入字段中,选择它,复制它并再次删除临时隐藏输入字段。

但它什么也没复制。?

let copyValue = document.getElementById(args.target).dataset.password;

document.body.insertAdjacentHTML('beforeend', `<input hidden id="temp-copy" value="${copyValue}">`);

let copyText = document.getElementById('temp-copy');

copyText.select();

document.execCommand("copy");

copyText.remove();

【问题讨论】:

    标签: javascript ecmascript-6 clipboard execcommand


    【解决方案1】:

    复制命令将当前选择复制到剪贴板。因此,您需要在复制之前选择输入中的文本:

    let input = document.getElementById(args.target);
    input.select();
    document.execCommand("Copy");
    

    如果该命令不受支持或未启用,您可能还需要检查execCommand 的返回值false。

    更新

    如果您尝试复制的节点不是input 或textarea,您可以选择它的文本,如下所示:

    var range = document.createRange();
    var selection = window.getSelection();
    range.selectNodeContents(document.getElementById('p'));
    
    selection.removeAllRanges();
    selection.addRange(range);
    

    source

    【讨论】:

    • 是的,但据我所知,不可能在 p htmltag 上调用 select 方法。我试过了,它抛出一个错误 copyText.select is not a function
    • @IlarioEngler 在这种情况下 - stackoverflow.com/a/25456308/1401662
    • 谢谢,我也发现了。但是文本在数据属性中
    • 正如我在原始问题中所写:我想从 html 元素中复制数据集中的一些内容。
    【解决方案2】:

    请参考 Dean Taylor 的回答:https://stackoverflow.com/a/30810322/2879085

    这是一个工作示例:

    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 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 IE the element
      // is visible whilst the popup box asking the user for permission for
      // the web page to copy to the clipboard.
      //
    
      // Place in 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 white box if rendered for any reason.
      textArea.style.background = 'transparent';
    
    
      textArea.value = text;
    
      document.body.appendChild(textArea);
    
      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 copyPasswordBtn = document.querySelector('button.mdl-button.mdl-js-button.mdl-button--icon');
    copyPasswordBtn.addEventListener('click', function(event) {
      var password = document.getElementById('web-password').dataset.password
      console.log(password)
      copyTextToClipboard(password);
    });
    <p id="web-password" data-password="my-secret-password" 
    data-state="0"></p>
    
    <button class="mdl-button mdl-js-button mdl-button--icon">
    
        <i data-event="copy" data-obj="util" data-target="web-password" 
        class="material-icons clickable-icon">content_copy</i>
    
    </button>
    
    <p>
      <textarea cols="50" rows="10">Try pasting into here to see what you have on your clipboard:
      
      </textarea>
    </p>

    【讨论】:

    • 最新的 Chrome 浏览器
    • 我在 iOS 11 上的移动 safari 上试过这个,不行。
    【解决方案3】:

    解决方案

    更新

    更好的解决方案。

    copyPassword (args) {
    
        function handler(event) {
    
            event.clipboardData.setData('text/plain', document.getElementById(args.target).dataset.password);
    
            event.preventDefault();
    
            document.removeEventListener('copy', handler, true);
        }
    
        document.addEventListener('copy', handler, true);
    
        document.execCommand('copy');
    }
    

    另类。 这也有效。

    let range = document.createRange();
    
    let selection = window.getSelection();
    
    let password = document.getElementById(args.target).dataset.password;
    
    document.body.insertAdjacentHTML('beforeend', `<p id="temp-copy">${password}</p>`);
    
    let node = document.getElementById('temp-copy');
    
    range.selectNodeContents(node);
    
    selection.removeAllRanges();
    
    selection.addRange(range);
    
    document.execCommand("copy");
    
    document.getElementById('temp-copy').remove();
    

    【讨论】:

      猜你喜欢
      • 2015-02-16
      • 2015-10-14
      • 1970-01-01
      • 2013-05-13
      • 1970-01-01
      • 2011-05-13
      • 1970-01-01
      • 2011-01-13
      相关资源
      最近更新 更多