-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathcontent-script.ts
49 lines (42 loc) · 1.26 KB
/
content-script.ts
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
import { createServer } from '@delight-rpc/webextension'
import { IFrameAPI, SpecialMessage } from '@src/contract.js'
import { isDev } from '@utils/is-dev.js'
if (isDev()) {
console.info(`[${chrome.runtime.getManifest().name}] The content script is injected`)
}
window.addEventListener('focus', async () => {
try {
await chrome.runtime.sendMessage(SpecialMessage.UpdateActiveFrameId)
} catch (e) {
if (isDev()) {
console.error(e)
}
}
})
createServer<IFrameAPI>({
getActiveElementTextContent
, getDocumentTitle
, getSelectionHTML
, getSelectionText
})
function getSelectionHTML(): string | null {
const userSelection = window.getSelection()
if (userSelection && userSelection.rangeCount) {
const range = userSelection.getRangeAt(0)
const clonedSelection = range.cloneContents()
const div = document.createElement('div')
div.appendChild(clonedSelection)
return div.innerHTML
} else {
return null
}
}
function getSelectionText(): string | null {
return window.getSelection()?.toString() ?? null
}
function getActiveElementTextContent(): string | null {
return document.activeElement?.textContent ?? null
}
function getDocumentTitle(): string {
return document.title
}