-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontent.js
More file actions
80 lines (63 loc) · 2.09 KB
/
content.js
File metadata and controls
80 lines (63 loc) · 2.09 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
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "insertLipsum") {
insertLipsumText(request.menuId);
}
});
function insertLipsumText(menuId) {
const [type, countStr] = menuId.split('-');
const count = parseInt(countStr);
const typeMap = {
'words': 'word',
'sentences': 'sentence',
'paragraphs': 'paragraph'
};
const text = window.Lipsum.get({
type: typeMap[type],
quantity: count,
hasPrefix: false,
textTransform: 'capitalizeFirstWordInSentence'
});
const activeElement = document.activeElement;
if (!activeElement) return;
if (activeElement.isContentEditable) {
insertIntoContentEditable(activeElement, text);
} else if (activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA') {
insertIntoInput(activeElement, text);
}
}
function insertIntoInput(element, text) {
const start = element.selectionStart;
const end = element.selectionEnd;
const currentValue = element.value;
const newValue = currentValue.slice(0, start) + text + currentValue.slice(end);
const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
window.HTMLInputElement.prototype,
"value"
).set;
const nativeTextAreaValueSetter = Object.getOwnPropertyDescriptor(
window.HTMLTextAreaElement.prototype,
"value"
).set;
if (element.tagName === 'TEXTAREA') {
nativeTextAreaValueSetter.call(element, newValue);
} else {
nativeInputValueSetter.call(element, newValue);
}
element.dispatchEvent(new Event('input', { bubbles: true }));
const newCursorPos = start + text.length;
element.setSelectionRange(newCursorPos, newCursorPos);
element.focus();
}
function insertIntoContentEditable(element, text) {
const selection = window.getSelection();
if (!selection.rangeCount) return;
const range = selection.getRangeAt(0);
range.deleteContents();
const textNode = document.createTextNode(text);
range.insertNode(textNode);
range.setStartAfter(textNode);
range.setEndAfter(textNode);
selection.removeAllRanges();
selection.addRange(range);
element.focus();
}