Javascript copy to clipboard

时间:2015-06-15 15:17:38

标签: javascript webforms .net-3.5

I am trying to copy some text to clipboard in a web page. I set a textbox, with its display set to "none" and populate it with some text. Then when I button is clicked, I try to set the clipboard to its content but I keep getting null.

I tried two ways of setting the clipboard: set the value of a hidden field "hfCTC" and calling ShowCTC2() and setting the value of input "ToCopy" and calling ShowCTC() and the alert shows null in both cases.

I don't want the button to do a postback, so I return false in js functions.

<input type="text" id="ToCopy" style="display:none" />
<asp:HiddenField runat="server" ID="hfCTC" />
<input type="image" id="ibCTC" src="images/CTC.png" onclick="return ShowCTC();"  />

function ShowCTC2(){
    if (document.all) // IE only
    {
        if (window.clipboardData && clipboardData.setData)
        {
            var ctrl = document.getElementById('<%=hfCTC.ClientID %>');
            var textToCopy = ctrl.value;
            window.clipboardData.setData('Text', ctrl.text);
            alert (window.clipboardData.getData ('Text'));
        }
    }
    return false;
}

function ShowCTC(){
    if (document.all) // IE only
    {
        window.clipboardData.clearData ("Text");
        select_all();
        alert (window.clipboardData.getData ('Text'));
    }
    return false;
}
function select_all() {
    var text_val = document.getElementById('ToCopy');
    text_val.focus();
    text_val.select();
    if (!document.all) return; // IE only
    r = text_val.createTextRange();
    r.execCommand('copy');
}

If I comment out the clearing of clipboard line in ShowCTC() and do a manual Ctl-C to copy something, the alert shows what I copied but the setting of clipboard data through code seems to fail.

1 个答案:

答案 0 :(得分:0)

这篇文章解决了这个问题:

MSIE and addEventListener Problem in Javascript?

我将代码更改为以下内容:

var $head = $("head");
var $headlinklast = $head.find("link[rel='stylesheet']:last");
var newlinkElement = "<link rel='stylesheet' href='/css/yourFile.css' type='text/css' media='screen'>";
if ($headlinklast.length){
   $headlinklast.after(newlinkElement);
}
else {
   $head.append(newlinkElement);
}