clipboard access in JavaScript

it is nothing new, but copying data to the clipboard in JavaScript is possible. the new thing is: the modern browsers handle this very intelligent on a per-domain base. so if some script tries to access the clipboard for reading or writing, the browser asks for permission for this domain. you can allow this to sites you trust. unfortunately Opera does not support this and as they mentioned they do not plan in the future. their argument is, that script kiddies will annoy people with permission-questions, so the best is to disallow it at all. and we have to say that there are more important things to implement, like SVG, CSS 3 and many more. here is a snippet that works fine in Internet Explorer 7 and Firefox 2:

function copy2clipboard(text) {
        if (window.clipboardData) window.clipboardData.setData("Text", text);
        else if (window.netscape) {
                netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
                var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
             if (!clip) return false;
                var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
                if (!trans) return false;
                trans.addDataFlavor('text/unicode');
                var str = new Object();
                var len = new Object();
                var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
                str.data=text;
                trans.setTransferData("text/unicode",str,text.length*2);
                var clipid=Components.interfaces.nsIClipboard;
                if (!clipid) return false;
                clip.setData(trans,null,clipid.kGlobalClipboard);
        }
        return false;
}

Saturday, 31. March 2007 • trackback url

Add Comment

( to reply to a comment, click the reply link next to the comment )

Comment Title:
Your Name:
Email Address:
Make Public?
Website:
Make Public?

Comment:


Allowed XHTML tags : a, b, i, strong, code, acrynom, blockquote, abbr. Linebreaks will be converted automatically.


Captcha:

captcha image

please type the content of the above image into the following form-field: