-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathoffscreen.js
More file actions
74 lines (68 loc) · 2.23 KB
/
offscreen.js
File metadata and controls
74 lines (68 loc) · 2.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* @file offscreen.js
* @description Script for the offscreen document to handle DOM-related tasks like clipboard access.
*/
class OffscreenManager {
constructor() {
this.clipboardTextarea = document.getElementById('clipboard-textarea');
this.initialize();
}
initialize() {
console.log('Offscreen Document: Initialized.');
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
this.handleMessage(message)
.then(response => sendResponse({
success: true,
data: response
}))
.catch(error => sendResponse({
success: false,
error: error.message
}));
return true; // Keep message channel open for async response.
});
}
async handleMessage(request) {
const {
action,
data
} = request;
switch (action) {
case 'clipboard-write':
return this.writeToClipboard(data.text);
case 'clipboard-read':
return this.readFromClipboard();
default:
throw new Error(`Unknown offscreen action: ${action}`);
}
}
async writeToClipboard(text) {
try {
this.clipboardTextarea.value = text;
this.clipboardTextarea.select();
document.execCommand('copy');
return {
status: 'success'
};
} catch (error) {
console.error('Offscreen: Clipboard write failed.', error);
throw new Error('Could not write to clipboard.');
} finally {
this.clipboardTextarea.value = '';
}
}
async readFromClipboard() {
try {
this.clipboardTextarea.value = '';
this.clipboardTextarea.focus();
document.execCommand('paste');
return this.clipboardTextarea.value;
} catch (error) {
console.error('Offscreen: Clipboard read failed.', error);
throw new Error('Could not read from clipboard.');
} finally {
this.clipboardTextarea.value = '';
}
}
}
new OffscreenManager();