UNPKG

3.28 kBJavaScriptView Raw
1/**
2 * 剪贴板部分的api参考了Chameleon项目的实现:
3 *
4 * setClipboardData: https://github.com/chameleon-team/chameleon-api/tree/master/src/interfaces/setClipBoardData
5 * getClipboardData: https://github.com/chameleon-team/chameleon-api/tree/master/src/interfaces/getClipBoardData
6 */
7var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
8 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
9 return new (P || (P = Promise))(function (resolve, reject) {
10 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
11 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
12 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
13 step((generator = generator.apply(thisArg, _arguments || [])).next());
14 });
15};
16import { MethodHandler } from '../../utils/handler';
17import { getStorageSync, setStorage, setStorageSync } from '../storage/index';
18const CLIPBOARD_STORAGE_NAME = 'taro_clipboard';
19document.addEventListener('copy', () => {
20 var _a;
21 setStorage({
22 key: CLIPBOARD_STORAGE_NAME,
23 data: (_a = window.getSelection()) === null || _a === void 0 ? void 0 : _a.toString()
24 }).catch(e => {
25 console.error(e);
26 });
27});
28/**
29 * 设置系统剪贴板的内容
30 */
31export const setClipboardData = ({ data, success, fail, complete }) => __awaiter(void 0, void 0, void 0, function* () {
32 const handle = new MethodHandler({ name: 'setClipboardData', success, fail, complete });
33 try {
34 setStorageSync(CLIPBOARD_STORAGE_NAME, data);
35 /**
36 * 已于 iPhone 6s Plus iOS 13.1.3 上的 Safari 测试通过
37 * iOS < 10 的系统可能无法使用编程方式访问剪贴板,参考:
38 * https://stackoverflow.com/questions/34045777/copy-to-clipboard-using-javascript-in-ios/34046084
39 */
40 if (typeof document.execCommand === 'function') {
41 const textarea = document.createElement('textarea');
42 textarea.readOnly = true;
43 textarea.value = data;
44 textarea.style.position = 'absolute';
45 textarea.style.width = '100px';
46 textarea.style.left = '-10000px';
47 document.body.appendChild(textarea);
48 textarea.select();
49 textarea.setSelectionRange(0, textarea.value.length);
50 document.execCommand('copy');
51 document.body.removeChild(textarea);
52 }
53 else {
54 throw new Error('Unsupported Function: \'document.execCommand\'.');
55 }
56 return handle.success();
57 }
58 catch (e) {
59 return handle.fail({ errMsg: e.message });
60 }
61});
62/**
63 * 获取系统剪贴板的内容
64 */
65export const getClipboardData = ({ success, fail, complete } = {}) => __awaiter(void 0, void 0, void 0, function* () {
66 const handle = new MethodHandler({ name: 'getClipboardData', success, fail, complete });
67 try {
68 const data = getStorageSync(CLIPBOARD_STORAGE_NAME);
69 return handle.success({ data });
70 }
71 catch (e) {
72 return handle.fail({ errMsg: e.message });
73 }
74});