# 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
}
}
```
示例代碼準備完畢之后,我們打開程序,如圖:

程序有三個按鈕,分別是獲取、寫入和清除剪貼板內容。在操作剪貼板之前,我們需要先獲取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類型。寫入和獲取都成功,會出現如下界面:

下面我們再看清楚內容的按鈕做了什么:
```
function clearText()
{
// And clear it!
clipboard.clear();
apendText('剪貼板內容已清除');
}
```
調用了clipboard.clear()方法,清除剪貼板,想要驗證是否清除成功,只需再次點擊獲取內容按鈕,看是否有內容輸出即可。

## 8.6 小結
本文內容主要參考node-webkit的官方英文文檔,做了適當的調整([https://github.com/rogerwang/node-webkit/wiki/Clipboard](https://github.com/rogerwang/node-webkit/wiki/Clipboard))。
下一篇文章,介紹Tray。
- 中文 Wiki
- 支持列表
- 開始nw.js
- package.json
- 中文教程
- node-webkit學習(1)hello world
- node-webkit學習(2)基本結構和配置
- node-webkit學習(3)Native UI API概覽
- node-webkit學習(4)Native UI API 之window
- node-webkit教程(5)Native UI API 之Frameless window
- node-webkit教程(6)Native UI API 之Menu(菜單)
- node-webkit教程(7)Platform Service之APP
- node-webkit教程(8)Platform Service之Clipboard
- node-webkit教程(9)native api 之Tray(托盤)
- node-webkit教程(10)Platform Service之File dialogs
- node-webkit教程(11)Platform Service之shell
- node-webkit教程(12)全屏
- node-webkit教程(13)gpu支持信息查看
- node-webkit教程(14)禁用緩存
- node-webkit教程(15)當圖片加載失敗的時候
- node-webkit教程(16)調試typescript