Copy Text to Clipboard - June 2009

I wanted to add a 'copy to clipboard' function to an application I'm writing. I did not know how to do this so I posted a question on the AspnetAnyQuestionIsOk Yahoo group. Rob Karatzas provided code that got me started. I decided to publish the code. I created a demo web project that uses JavaScript and a class modules called cCopyTextBoxTextToClipboard.vb. You can download the project by clicking a link shown below.

The Demo Project - Upon initiation the demo loads an Asp.Net text box with some lines of text. Click the 'Copy to Clipboard' button to initiate the copy action.


The number of characters copied to the clipboard is reported.

Warning Dialog - The following IE dialog is opened when the copy button is pressed. Click 'Allow Access' to copy the text to the clipboard.

Question - Is there anyway to prevent the dialog from being displayed? I have seen at least one web site that will copy stuff to the clipboard without displaying the dialog. Do you know how they do it? If you do I will add your code to this page and give you credit for it.

Operative Code - JavaScript code is added to the page. The code:

<head>
........
    <script type="text/javascript" language="javascript">
    function TextBoxToClipBoard(sTextBoxID)
{
    var data = document.getElementById(sTextBoxID).value;
    window.clipboardData.setData("Text",data);
}
    </script>
........
</head>

Code Behind Page - Typical code added to the VB.Net code behind page is:

With Me.ButtonCopy
    ....
    Dim oCTT As New cCopyTextBoxTextToClipboard
    .Attributes.Add(oCTT.GetOnClick, oCTT.GetJavascript(Me.TextBoxForClipboard.ID))
    ....
End With

Download VB.Net Code

Download - VS2005 VB.Net Zipped File  Size 
Copy Text To Clipboard CopyToClipboard.zip 29K

Previous Tip   Tip Index   Next Tip

Home

Updated 2011/12/28