🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# node-webkit教程(8)Platform Service之Clipboard > 作者:玄魂 > 来源:[node-webkit教程(8)Platform Service之Clipboard](http://www.cnblogs.com/xuanhun/p/3671461.html) ## 目录 + 8.1 Clipboard 操作 + 8.6 小结 ## 前言 ## 8.1 Clipboard 操作 Clipboard是对操作系统剪贴板的一个抽象,目前只支持获取和设置纯文本内容。 新建clip.html和package.json。 clip.html内容如下: ``` <html> <head> <title>appDemo</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body > <h1>app api 测试</h1> <button onclick="getText()">获取内容</button> <button onclick="setText()">写入内容</button> <button onclick="clearText()">清除内容</button> <script> var gui = require('nw.gui'); // We can not create a clipboard, we have to receive the system clipboard var clipboard = gui.Clipboard.get(); function apendText(text) { var element = document.createElement('div'); element.appendChild(document.createTextNode(text)); document.body.appendChild(element); } function clearText() { // And clear it! clipboard.clear(); apendText('剪贴板内容已清除'); } function setText() { // Or write something clipboard.set('这是node-webkit向剪贴板写的内容', 'text'); } function getText() { // Read from clipboard var text = clipboard.get('text'); apendText(text); } </script> </body> </html> ``` package.json内容如下: ``` { "name": "clip-demo", "main": "clip.html", "nodejs":true, "window": { "title": "clipDemo", "toolbar": true, "width": 800, "height": 600, "resizable":true, "show_in_taskbar":true, "frame":true, "kiosk":false, "icon": "2655716405282662783.png" }, "webkit":{ "plugin":true } } ``` 示例代码准备完毕之后,我们打开程序,如图: ![](img/171859144163776.png) 程序有三个按钮,分别是获取、写入和清除剪贴板内容。在操作剪贴板之前,我们需要先获取clipboard对象: ``` var clipboard = gui.Clipboard.get(); ``` 现在我们先单击第二个按钮,向剪贴板写入内容,代码如下: ``` function setText() { // Or write something clipboard.set('这是node-webkit向剪贴板写的内容', 'text'); } ``` clipboard.set方法接收两个参数,第一个参数是要写入的内容,第二个参数是内容类型,目前只支持text类型。 是否写入成功了呢?我们再单击第一个按钮,事件处理代码如下: ``` function getText() { // Read from clipboard var text = clipboard.get('text'); apendText(text); } ``` 第一个按钮通过clipboard.get方法获取剪贴板内容然后输出,get方法接收一个参数,指明内容类型,目前只支持text类型。写入和获取都成功,会出现如下界面: ![](img/171859200419557.png) 下面我们再看清楚内容的按钮做了什么: ``` function clearText() { // And clear it! clipboard.clear(); apendText('剪贴板内容已清除'); } ``` 调用了clipboard.clear()方法,清除剪贴板,想要验证是否清除成功,只需再次点击获取内容按钮,看是否有内容输出即可。 ![](img/171859260578753.png) ## 8.6 小结 本文内容主要参考node-webkit的官方英文文档,做了适当的调整([https://github.com/rogerwang/node-webkit/wiki/Clipboard](https://github.com/rogerwang/node-webkit/wiki/Clipboard))。 下一篇文章,介绍Tray。