faqts : Computers : Programming : Languages : JavaScript : Document

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

145 of 162 people (90%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

Can I read from the clipboard and write to it?
Can I copy a string (e.g. containing the value of document.myForm.outerHTML) to the windows clipboar

Apr 28th, 2004 04:50
Beninu Andersen, Juergen Thelen, Martin Honnen,


IE5 allows that with the
  window.clipboardData
object which has a 
  window.clipboardData.setData('Text', 'text to paste')
or
  window.clipboardData.setData('URL', 'http://www.faqts.com')
method to write data to the clipboard and a 
  var cbData = window.clipboardData.getData('Text')
respectively
  var cbData = window.clipboardData.getData('URL')
to read from the clipboard.
No such object is around in IE4.
NN4 with trusted script can call into java to access the clipboard.
*****
Sorry, Martin, but in my experience writing to the windows clipboard 
using window.clipboardData.setData('Text', 'text to paste') does not 
work with all IE5 versions (especially with versions before IE 5.5).
German IE 5.0 versions for example always crash when using this method.
My workaround to get rid of this bug is to use a textarea form field 
that holds the text to be copied, select it by form.textarea.select() 
method and copy it to the clipboard using the execCommand('Copy').
Unfortunately the select() method works with visible form objects only 
(would have preferred a solution with input type=hidden), but it's no 
problem for us to just move this form outta sight, right? :O)
Here's a quickie showing this technique:
--- snip ---
<html>
<head>
<title>FAQTS - Juergen Thelen - clipboardData.setData Workaround (IE5 
Win)</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body bgcolor="#FFFFFF">
<div id="Layer1" style="position:absolute; width:200px; height:115px; z-
index:1; left: -100px"> 
  <form name="theForm">
    <textarea name="theArea" cols="1">text to be copied</textarea>
  </form>
</div>
<script language="Javascript">
<!--
document.theForm.theArea.select();
document.execCommand('Copy');
//-->
</script>
</body>
</html>
--- snap ---
Just save the snippet as .htm file and load it with IE5. Nothing visual 
will happen (will show just a blank white page), but if you use Paste 
(Ctrl-V) anywhere - say in the address window, where you usually type 
in your URLs - you will see that the clipboard now holds the same text 
as the theForm.theTextArea does... ;o)
Hth, Juergen
---------------------
A small correction
If you don't want to use a method where you put the form out of the 
display (wich is, by the way, a bit goofy), you can just chose to make 
the above mentioned div invisivle, by the following syntax:
   Layer1.style.display = 'NONE';
Best regards
Beninu