工作剪贴板脚本与Chrome不兼容。与Edge / IE一起使用

时间:2019-09-12 14:30:12

标签: javascript google-chrome clipboard

我有一个有效的剪贴板脚本,必须在我们的门户页面上使用它才能利用剪贴板功能。我们正在从IE / Edge迁移到Chrome,看来该脚本无法在Google Chrome中运行。如果我们能找到一种方法来使代码chrome / multi浏览器兼容,而不必为仅适用于Chrome的浏览器创建新的脚本,我会很喜欢。

虽然我确实有一个适用于Chrome的脚本,但这意味着我将不得不使用剪贴板重新构建数百个页面,而我希望脚本已经嵌入所有这些页面中并与Chrome兼容。下面是我正在使用的脚本:

(function() {

    'use strict';

  // click events
  document.body.addEventListener('click', copy, true);

    // event handler
    function copy(e) {

    // find target element
    var 
      t = e.target,
      c = t.dataset.copytarget,
      inp = (c ? document.querySelector(c) : null);

    // is element selectable?
    if (inp && inp.select) {

      // select text
      inp.select();

      try {
        // copy text
        document.execCommand('copy');
        inp.blur();

        // copied animation
        t.classList.add('copied');
        setTimeout(function() { t.classList.remove('copied'); }, 1500);
      }
      catch (err) {
        alert('please press Ctrl/Cmd+C to copy');
      }

    }

    }

})();

// Button must include data-copytarget="#website" with the #xxx matching the element id

结果:在IE / Edge中,单击该按钮,然后将该按钮分配的文本添加到剪贴板中以进行粘贴。但是,在Chrome浏览器中,单击按钮并没有任何反应。

1 个答案:

答案 0 :(得分:0)

只要输入可见,您的代码即可在Chrome中正常运行。

Chrome不允许从隐藏的输入中进行复制。有多种解决方法。在下面的示例中,我使用绝对定位移动了屏幕的输入。

(function() {
  "use strict";

  // click events
  document.body.addEventListener("click", copy, true);

  // event handler
  function copy(e) {
    // find target element
    var t = e.target,
      c = t.dataset.copytarget,
      inp = c ? document.querySelector(c) : null;

    // is element selectable?
    if (inp && inp.select) {
      // select text
      inp.select();

      try {
        // copy text
        document.execCommand("copy");
        inp.blur();

        // copied animation
        t.classList.add("copied");
        setTimeout(function() {
          t.classList.remove("copied");
        }, 1500);
      } catch (err) {
        alert("please press Ctrl/Cmd+C to copy");
      }
    }
  }
})();
#vishidden {
  position: absolute;
  top: -9999px;
  left: -9999px;
}
<div>
  <input type="text" id="text" value="visible test" readonly="true">
  <button type="button" data-copytarget="#text">copy</button>
</div>

<div>
  <input type="hidden" id="hidden" value="hidden test" readonly="true">
  <button type="button" data-copytarget="#hidden">copy hidden</button>
</div>

<div>
  <input type="text" id="vishidden" value="visually hidden test" readonly="true">
  <button type="button" data-copytarget="#vishidden">copy visually hidden</button>
</div>

<div>
  <textarea cols="30" rows="10" placeholder="paste here to test"></textarea>
</div>

另一个示例:Using execCommand (Javascript) to copy hidden text to clipboard

Clipboard.js是执行此操作的有用库。它还在幕后使用了视觉上隐藏的输入(以与我的示例类似但更可靠的方式)。