-
Notifications
You must be signed in to change notification settings - Fork 9
/
background.js
49 lines (36 loc) · 1.28 KB
/
background.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
38
39
40
41
42
43
44
45
46
47
48
49
chrome.commands.onCommand.addListener(function (command) {
const MARKDOWN_LINK_TEMPLATE = "[$name]($href)"
var clipboardContent = getClipboardContents()
, markdownLink
getSelection(function (selection) {
markdownLink = MARKDOWN_LINK_TEMPLATE
.replace("$name", selection)
.replace("$href", clipboardContent)
chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, {action: "paste", data: markdownLink})
})
})
})
function getSelection(callback) {
chrome.tabs.query({active: true, currentWindow: true}, function (tabs) {
chrome.tabs.sendMessage(tabs[0].id, {action: "getSelection"}, function (response) {
callback(response.selection)
})
})
}
/**
* Not mine: something similar to this: https://gist.github.com/bitoiu/9358481bc38db67b32ff
**/
function getClipboardContents() {
var pasteTarget
, pasteTargetParent
, clipboardContent
pasteTarget = document.createElement("div")
pasteTarget.contentEditable = true
pasteTargetParent = document.activeElement.appendChild(pasteTarget).parentNode
pasteTarget.focus()
document.execCommand("Paste", null, null)
clipboardContent = pasteTarget.innerText
pasteTargetParent.removeChild(pasteTarget)
return clipboardContent
}