Skip to content

Commit 972ff97

Browse files
author
Avaer Kazmer
committed
Add initial clipboard management implementation
1 parent 98f4374 commit 972ff97

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

app.html

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,58 @@
9696
function escapeRegExp(s) {
9797
return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
9898
}
99+
const clipboard = {
100+
copy(text) {
101+
const fakeElem = document.body.appendChild(document.createElement('textarea'));
102+
fakeElem.style.position = 'absolute';
103+
fakeElem.style.left = '-9999px';
104+
fakeElem.setAttribute('readonly', '');
105+
fakeElem.value = text;
106+
fakeElem.select();
107+
try {
108+
return document.execCommand('copy');
109+
} catch (err) {
110+
return false;
111+
} finally {
112+
fakeElem.parentNode.removeChild(fakeElem);
113+
}
114+
},
115+
paste() {
116+
const fakeElem = document.body.appendChild(document.createElement('textarea'));
117+
fakeElem.style.position = 'absolute';
118+
fakeElem.style.left = '-9999px';
119+
fakeElem.setAttribute('readonly', '');
120+
fakeElem.select();
121+
fakeElem.parentNode.removeChild(fakeElem);
122+
123+
return navigator.clipboard.readText()
124+
.catch(err => {
125+
console.warn(err);
126+
127+
return navigator.permissions.query({
128+
name: 'clipboard-read',
129+
})
130+
.then(async permissionStatus => {
131+
// Will be 'granted', 'denied' or 'prompt':
132+
console.log('permission 1', permissionStatus.state);
133+
134+
if (permissionStatus.state !== 'granted') {
135+
// Listen for changes to the permission state
136+
await new Promise((accept, reject) => {
137+
permissionStatus.onchange = () => {
138+
console.log('permission 2', permissionStatus.state);
139+
if (permissionStatus.state === 'granted') {
140+
permissionStatus.onchange = null;
141+
accept();
142+
}
143+
};
144+
});
145+
}
146+
})
147+
.then(() => navigator.clipboard.readText());
148+
});
149+
},
150+
};
99151

100152
const _makeNullPromise = () => {
101153
let resolve, reject;

0 commit comments

Comments
 (0)