-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinjected-script.js
More file actions
367 lines (324 loc) · 9.83 KB
/
injected-script.js
File metadata and controls
367 lines (324 loc) · 9.83 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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
// Canvas Editor DevTools - Injected Script
// Directly inject into page, interact with Editor instance
(function () {
'use strict'
// Safely serialize data, remove non-cloneable objects (Promise, functions, DOM elements, etc.)
function safeSerialize(obj, maxDepth = 3, currentDepth = 0) {
if (currentDepth > maxDepth) return '[Max Depth]'
if (obj === null || obj === undefined) return obj
if (typeof obj === 'function') return '[Function]'
if (obj instanceof Promise) return '[Promise]'
if (obj instanceof HTMLElement) return '[HTMLElement]'
if (obj instanceof Node) return '[Node]'
if (obj instanceof Window) return '[Window]'
if (obj instanceof Document) return '[Document]'
// Process array
if (Array.isArray(obj)) {
return obj.map(item => safeSerialize(item, maxDepth, currentDepth + 1))
}
// Process date
if (obj instanceof Date) return obj.toISOString()
// 处理正则
if (obj instanceof RegExp) return obj.toString()
// 处理普通对象
if (typeof obj === 'object') {
const result = {}
try {
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
// Skip private properties starting with _
if (key.startsWith('_')) continue
try {
const value = obj[key]
result[key] = safeSerialize(value, maxDepth, currentDepth + 1)
} catch (e) {
result[key] = '[Error: ' + e.message + ']'
}
}
}
} catch (e) {
return '[Object Error]'
}
return result
}
return obj
}
// Wrap command methods to track calls
function wrapCommands() {
const editor = window.__CANVAS_EDITOR_INSTANCE__
if (!editor || editor.__devtools_wrapped__) {
return
}
const command = editor.command
const originalMethods = {}
// Record all execute* and get* methods
Object.keys(command).forEach(key => {
if (typeof command[key] !== 'function') return
if (!key.startsWith('execute') && !key.startsWith('get')) return
originalMethods[key] = command[key]
command[key] = function (...args) {
const startTime = performance.now()
const type = key.startsWith('execute') ? 'command' : 'query'
// Safely serialize arguments
const safeArgs = args.map(arg => safeSerialize(arg, 2))
try {
const result = originalMethods[key].apply(command, args)
const duration = Math.round(performance.now() - startTime)
// Send command execution info
const sendCommandInfo = (res, dur, isAsync) => {
window.postMessage(
{
source: 'canvas-editor-devtools-page',
type: 'COMMAND_EXECUTED',
payload: {
type: type,
name: key,
args: safeArgs,
duration: dur,
result: type === 'query' ? safeSerialize(res, 3) : undefined,
isAsync: isAsync,
timestamp: Date.now()
}
},
'*'
)
}
// Handle Promise result
if (result instanceof Promise) {
result.then(
resolvedValue => {
sendCommandInfo(
resolvedValue,
Math.round(performance.now() - startTime),
true
)
},
rejectedError => {
window.postMessage(
{
source: 'canvas-editor-devtools-page',
type: 'COMMAND_ERROR',
payload: {
name: key,
error: rejectedError?.message || 'Promise rejected',
isAsync: true,
timestamp: Date.now()
}
},
'*'
)
}
)
} else {
sendCommandInfo(result, duration, false)
}
return result
} catch (error) {
window.postMessage(
{
source: 'canvas-editor-devtools-page',
type: 'COMMAND_ERROR',
payload: {
name: key,
error: error.message,
timestamp: Date.now()
}
},
'*'
)
throw error
}
}
})
// Mark as wrapped
editor.__devtools_wrapped__ = true
}
// Store event handler references for later removal
const eventHandlers = new Map()
// Listen for events
function setupEventListeners() {
const editor = window.__CANVAS_EDITOR_INSTANCE__
if (!editor || !editor.eventBus || typeof editor.eventBus.on !== 'function') {
return false
}
// If already set, remove old listener first
if (eventHandlers.size > 0) {
removeAllEventListeners()
}
// Reference eventbus.md documentation to define all supported events
const eventDefinitions = [
'contentChange',
'rangeStyleChange',
'visiblePageNoListChange',
'intersectionPageNoChange',
'pageSizeChange',
'pageScaleChange',
'controlChange',
'controlContentChange',
'pageModeChange',
'saved',
'zoneChange',
'positionContextChange',
'imageSizeChange',
'imageMousedown',
'imageDblclick',
'labelMousedown',
// Mouse events
'mousemove',
'mouseenter',
'mouseleave',
'mousedown',
'mouseup',
'click',
'input'
]
eventDefinitions.forEach(eventName => {
const handler = data => {
window.postMessage(
{
source: 'canvas-editor-devtools-page',
type: 'EVENT_EMITTED',
payload: {
event: eventName,
data: safeSerialize(data),
timestamp: Date.now()
}
},
'*'
)
// Trigger data update on contentChange
if (eventName === 'contentChange') {
window.postMessage(
{
source: 'canvas-editor-devtools-page',
type: 'NEED_REFRESH_DATA'
},
'*'
)
}
}
// Store handler reference
eventHandlers.set(eventName, handler)
// Register event listener
try {
editor.eventBus.on(eventName, handler)
} catch (e) {
// ignore
}
})
return true
}
// Remove all event listeners
function removeAllEventListeners() {
const editor = window.__CANVAS_EDITOR_INSTANCE__
if (!editor || !editor.eventBus || typeof editor.eventBus.off !== 'function') {
eventHandlers.clear()
return
}
eventHandlers.forEach((handler, eventName) => {
try {
editor.eventBus.off(eventName, handler)
} catch (e) {
// Ignore removal error
}
})
eventHandlers.clear()
}
// Get editor data - use correct API
function getEditorData() {
const editor = window.__CANVAS_EDITOR_INSTANCE__
if (!editor) return null
const command = editor.command
try {
// Use getValue to get complete document data
const value = command.getValue ? command.getValue() : null
const options = command.getOptions ? command.getOptions() : null
const range = command.getRange ? command.getRange() : null
const rangeContext = command.getRangeContext
? command.getRangeContext()
: null
return {
version: editor.version,
options: options,
range: range,
rangeContext: rangeContext,
// Document data
data: value
? {
header: value.data?.header || [],
main: value.data?.main || [],
footer: value.data?.footer || []
}
: { header: [], main: [], footer: [] }
}
} catch (e) {
return null
}
}
// Listen for messages from content script
window.addEventListener('message', function (event) {
if (event.source !== window) return
if (!event.data || event.data.source !== 'canvas-editor-devtools-content')
return
const payload = event.data.payload
switch (payload?.action) {
case 'GET_DATA': {
const rawData = getEditorData()
const safeData = safeSerialize(rawData, 5)
window.postMessage(
{
source: 'canvas-editor-devtools-page',
type: 'EDITOR_DATA',
payload: safeData
},
'*'
)
break
}
case 'EXECUTE_COMMAND': {
const editor = window.__CANVAS_EDITOR_INSTANCE__
if (editor && payload.command) {
editor.command[payload.command](...payload.args)
}
break
}
}
})
// Initialize
function init() {
// Check immediately once
if (window.__CANVAS_EDITOR_INSTANCE__) {
wrapCommands()
setupEventListeners()
return
}
// Wait for Editor instance
let attempts = 0
const maxAttempts = 120 // Wait at most 60 seconds
const checkInterval = setInterval(() => {
attempts++
if (window.__CANVAS_EDITOR_INSTANCE__) {
clearInterval(checkInterval)
wrapCommands()
const success = setupEventListeners()
if (!success) {
// eventBus may not exist yet, continue trying
const eventBusInterval = setInterval(() => {
const eventBusSuccess = setupEventListeners()
if (eventBusSuccess) {
clearInterval(eventBusInterval)
}
}, 500)
}
} else if (attempts >= maxAttempts) {
clearInterval(checkInterval)
}
}, 500)
}
// Clean up when page unloads
window.addEventListener('beforeunload', () => {
removeAllEventListeners()
})
// Start initialization
init()
})()