Tuesday, April 10, 2012

How to read/write clipboard data in cross browser?


Copy To Clipboard (in FireFox)

clipboarddata.setdata firefox


The following script block will allows you to access clipboard in all browsers(i.e: IE, Firefox,Chrome, Safari).

    <script type="text/javascript">

  function CopyTest(copyString) {

            if (window.clipboardData) {
                //This Code block will be executed in IE(Microsoft Internet Explorer)
                window.clipboardData.setData("Text", meintext);
            }
            else if (window.netscape) {

                //Enabling Security alert and based on security alert confirmation accessing the clip board
                netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

                // Creating Instance to the Clipboard class and inheriting the "nsIClipboard" interface which is used to copy data into clip board
                var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
                if (!clip) return;

                // Creating Instance to the transferable class and inheriting the "nsITransferable" interface which is used to transfer data
                var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
                if (!trans) return;

                // Specifying content type ex:'text/unicode' or 'html'
                trans.addDataFlavor('text/unicode');

                //Creating two objects first object used to store input string and another object is used to store  length of the string
                var str = new Object();
                var len = new Object();

                // Creating Instance to the supports-string class and inheriting the "nsISupportsString" interface which is used to copy data into clip board
                var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);
                str.data = copyString;
                trans.setTransferData("text/unicode", str, copyString.length * 2);
                var clipid = Components.interfaces.nsIClipboard;

                if (!clip) return false;
                clip.setData(trans, null, clipid.kGlobalClipboard);

            }
        }
</script>

Demo:


Download Clip board Data Sample

No comments:

Post a Comment