Repository navigation
Expand file tree
/
Copy pathcontent.js
More file actions
104 lines (87 loc) · 2.62 KB
/
Copy pathcontent.js
File metadata and controls
104 lines (87 loc) · 2.62 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
// Content script that runs on CodePen pages (in isolated world)
// Communicates with inject.js (which runs in main world) via window.postMessage
// Notify background script that content is ready
chrome.runtime.sendMessage({ type: 'CONTENT_READY' });
// Message passing between isolated world (content.js) and main world (inject.js)
let messageId = 0;
const pendingMessages = new Map();
window.addEventListener('message', (event) => {
if (event.source !== window) return;
const message = event.data;
if (message.source !== 'chrome-code-inject') return;
const resolve = pendingMessages.get(message.id);
if (resolve) {
resolve(message.result);
pendingMessages.delete(message.id);
}
});
function sendToMainWorld(action, data = {}) {
return new Promise((resolve) => {
const id = messageId++;
pendingMessages.set(id, resolve);
window.postMessage({
source: 'chrome-code-content',
id,
action,
...data
}, '*');
// Timeout after 1 second
setTimeout(() => {
if (pendingMessages.has(id)) {
pendingMessages.delete(id);
resolve(null);
}
}, 1000);
});
}
async function checkEditorsReady() {
return await sendToMainWorld('checkReady');
}
async function getAllCode() {
return await sendToMainWorld('getAllCode');
}
async function setCode(editorType, code, changedLines) {
return await sendToMainWorld('setCode', { editorType, code, changedLines });
}
// Listen for messages from the background script
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === 'GET_CODE') {
getAllCode().then(code => {
sendResponse({
success: true,
code: code
});
});
return true; // Will respond asynchronously
}
if (message.type === 'UPDATE_CODE') {
setCode(message.editor, message.code, message.changedLines).then(success => {
sendResponse({
success: success
});
});
return true; // Will respond asynchronously
}
return true;
});
// Monitor for CodePen editor initialization
// Sometimes editors aren't ready immediately
let retryCount = 0;
const maxRetries = 10;
async function checkEditorsReadyLoop() {
const ready = await checkEditorsReady();
if (ready) {
chrome.runtime.sendMessage({ type: 'CONTENT_READY' });
} else if (retryCount < maxRetries) {
retryCount++;
setTimeout(checkEditorsReadyLoop, 1000);
}
}
// Wait for page to be fully loaded
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', () => {
setTimeout(checkEditorsReadyLoop, 1000);
});
} else {
setTimeout(checkEditorsReadyLoop, 1000);
}