使用execCommand(Javascript)将隐藏文本复制到剪贴板 [英] Using execCommand (Javascript) to copy hidden text to clipboard

查看:1070
本文介绍了使用execCommand(Javascript)将隐藏文本复制到剪贴板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在不使用Flash的情况下复制到剪贴板,我打算使用 ZeroClipboard 如果浏览器与javascript方法不兼容



我有一个按钮的onClick侦听器,如下所示:



($); $ b $ copyDiv.focus(); $ b $($) b document.execCommand('SelectAll');
document.execCommand(Copy,false,null);
}

和一个输入字段如下:

 < input type =text name =要复制的元素id =inputContainingTextToBeCopiedvalue =foo/> 

这目前正如预期的那样工作,但设计要求包含要复制的文本的字段是不可见的。我已经尝试将 type =hidden style =display:none都没有成功。这两个都导致按钮选择整个页面,并将整个内容复制到用户的剪贴板。

我相对有信心的原因不是基于浏览器,但只是incase,我在Chrome上测试(版本43.0。 2357.134(64位))在Mac OS X 10.10.4上。



有没有一种方法可以保持<输入>隐藏它时是可见的?或者如果不是我可以采取的替代路线?






我知道类似的问题,其中没有一个解决我的问题,不是太旧,就是实际上没有使用Javascript或者不适合特定的场景。 这里有一个很好的答案,适用于任何有类似问题的人。

解决方案

- 更新 -




Document.execCommand()



[1]在Firefox 41之前,需要在user.js首选项文件中启用剪贴板功能。请参阅 Mozilla偏好设置获取更多信息的简要指南。如果该命令不受支持或未启用,execCommand引发异常而不是返回false。在Firefox 41及更高版本中,默认情况下在任何能够弹出窗口的事件处理程序中启用剪贴板功能(半可信脚本)。


Firefox版本41 现在可以使用Document.execCommand()。因此,不必再使用回退。






由于浏览器在剪贴板访问时似乎有不同的表现,因此$

这与您的解决方案非常相似,不同的是创建一个临时元素并填充它输入。这样我们可以将输入的显示属性设置为 none



对于 IE 也有一个解决方法,它使用 window.clipboardData



Firefox 根本不允许我访问剪贴板。所以我不得不添加提示符来让用户手动复制输入值。确保提示符很丑,但是您可以使用像窗口这样的模式,它可以做到这一点。



由于这似乎是一个棘手的问题,我在 Win7(64位)上进行了测试,并在
$ b Chrome中进行了测试 - 版本43.0.2357.134米



IE - 版本11.0.9600.17914

=jsdata-hide =falsedata-console =falsedata-babel =false>

 

#copy-me {display:none}

< ; script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js>< / script>< input type =textname =Element To be Copiedid =copy-mevalue =foo loves bar/>< button id =copy-btn>复制< / button>< br />< br /> < / textarea>


I'm trying to copy to clipboard without using Flash, I plan to fall back onto Flash with the use of ZeroClipboard if the browser is incompatible with the javascript approach.

I have an onClick listener for the button which looks like:

$(buttonWhereActionWillBeTriggered).click(function(){ 
    var copyDiv = document.getElementById(inputContainingTextToBeCopied);
    copyDiv.focus();
    document.execCommand('SelectAll');
    document.execCommand("Copy", false, null);
}

and an input field as follows:

<input type="text" name="Element To Be Copied" id="inputContainingTextToBeCopied" value="foo"/>

This currently works as expected but the design requires that the field containing the text to be copied is invisible. I have tried both setting type="hidden" and style="display: none" neither of which have succeeded. Both resulting in the button selecting the whole page and copying the whole content to the user's clipboard.
I'm relatively confident the cause is not browser based but just incase, I am testing on Chrome (Version 43.0.2357.134 (64-bit)) on Mac OS X 10.10.4.

Is there a way that I can maintain the functionality of when the < input> is visible whilst hiding it? or if not an alternate route I can take?


I'm aware of similar questions, none of which address my problem, either from being too old, not actually using Javascript or not fitting the particular scenario. Here's a good answer for anyone having similar, less specific issues.

解决方案

--Update--

Document.execCommand()

[1] Before Firefox 41, clipboard capability needed to be enabled in the user.js preference file. See A brief guide to Mozilla preferences for more information. If the command wasn't supported or enabled, execCommand was raising an exception instead of returning false.In Firefox 41 and later, clipboard capability are enabled by default in any event handler that is able to pop-up a window (semi-trusted scripts).

Since Firefox version 41 Document.execCommand() now works. So no need to use a fallback anymore.


Since browsers seem to behave differently when it comes to the clipboard access, it took me a while to get my head around it.

It's pretty similar to your solution, but the difference is to create a temporary element and fill it with the input value. That way we can keep the input's display property set to none.

There is also a workaround for IE which uses window.clipboardData.

Firefox would not let me access the clipboard at all. So i had to add a prompt to let users manually copy the input value. Sure a prompt is ugly, but you could just use a modal like window, which would do the same.

Since this seems to be a knotty thing, i am on Win7 (64 bit) and tested in

Chrome - Version 43.0.2357.134 m

IE - Version 11.0.9600.17914

and Firefox is irrelevant, because it would not let me access it anyway.

var copyBtn   = $("#copy-btn"),
    input     = $("#copy-me");

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

function copyToClipboard() {
  var success   = true,
      range     = document.createRange(),
      selection;

  // For IE.
  if (window.clipboardData) {
    window.clipboardData.setData("Text", input.val());        
  } else {
    // Create a temporary element off screen.
    var tmpElem = $('<div>');
    tmpElem.css({
      position: "absolute",
      left:     "-1000px",
      top:      "-1000px",
    });
    // Add the input value to the temp element.
    tmpElem.text(input.val());
    $("body").append(tmpElem);
    // Select temp element.
    range.selectNodeContents(tmpElem.get(0));
    selection = window.getSelection ();
    selection.removeAllRanges ();
    selection.addRange (range);
    // Lets copy.
    try { 
      success = document.execCommand ("copy", false, null);
    }
    catch (e) {
      copyToClipboardFF(input.val());
    }
    if (success) {
      alert ("The text is on the clipboard, try to paste it!");
      // remove temp element.
      tmpElem.remove();
    }
  }
}

copyBtn.on('click', copyToClipboard);

#copy-me {
    display:none
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="Element To Be Copied" id="copy-me" value="foo loves bar"/>
<button id="copy-btn">Copy</button><br/><br/>
<textarea placeholder="paste here"></textarea>

这篇关于使用execCommand(Javascript)将隐藏文本复制到剪贴板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆