javascript cut/copy/paste to clipboard: how did Google solve it?

前端 未结 5 1953
半阙折子戏
半阙折子戏 2020-12-04 13:48

Yes, this question has been asked again and again: how to copy and paste from and to the system clipboard with javascript? I have found only partial solutions and hacks so f

5条回答
  •  眼角桃花
    2020-12-04 14:20

    As an addition to what others have already posted in this thread I've created a fully working example that demonstrates keyboard shortcut approach (CTRL+C or CMD+C on Mac OS X) as well as custom button approach which triggers the copy action.

    Full demo can be found here: http://jsfiddle.net/rve7d/

    I found Mateusz W answer very useful while trying to create this demo but he hasn't taken into consideration support for IE which behaves slightly different and uses different data types as a first parameter.

    if(window.clipboardData) {
        // use just 'Text' or 'Url' as a first param otherwise strange exception is thrown
        window.clipboardData.setData('Text', 'Text that will be copied to CB');        
    } else if(ev.originalEvent.clipboardData) {
        ev.originalEvent.clipboardData.setData('text/plain', 'Text that will be copied to CB');      
    } else {
        alert('Clipboard Data are not supported in this browser. Sorry.');
    }
    

    PS: I needed this functionality for our custom Spreadsheet View component and on the way analysed the source code of Google Spreadsheets so my solution mostly conforms to their solution.

提交回复
热议问题