-
Notifications
You must be signed in to change notification settings - Fork 0
/
contentscript.js
37 lines (34 loc) · 1.27 KB
/
contentscript.js
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
//https://gist.github.com/srsudar/e9a41228f06f32f272a2
'use strict';
/**
* Insert the text at the cursor into the active element. Note that we're
* intentionally not appending or simply replacing the value of the editable
* field, as we want to allow normal pasting conventions. If you paste at the
* beginning, you shouldn't see all your text be replaced.
* Taken from:
* http://stackoverflow.com/questions/7404366/how-do-i-insert-some-text-where-the-cursor-is
*/
function insertTextAtCursor(text) {
var el = document.activeElement;
var val = el.value;
var endIndex;
var range;
var doc = el.ownerDocument;
if (typeof el.selectionStart === 'number' &&
typeof el.selectionEnd === 'number') {
endIndex = el.selectionEnd;
el.value = val.slice(0, endIndex) + text + val.slice(endIndex);
el.selectionStart = el.selectionEnd = endIndex + text.length;
} else if (doc.selection !== 'undefined' && doc.selection.createRange) {
el.focus();
range = doc.selection.createRange();
range.collapse(false);
range.text = text;
range.select();
}
}
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.data) {
insertTextAtCursor(request.data);
}
});