-
Notifications
You must be signed in to change notification settings - Fork 4
/
background.js
79 lines (71 loc) · 2.52 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
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
// localStorage.clear(); // bust cached settings
// instantiate default settings
var settings = new Store("settings", {
"strip_elements": "div, span, small, aside, section, article, header, footer, hgroup, time, address, button",
"delete_elements": "script, noscript, canvas, embed, object, param, svg, source, nav, iframe, details"
});
// instantiate a context menu (right click)
chrome.runtime.onInstalled.addListener(function() {
chrome.contextMenus.create({
title: "Get Markdown",
id: "getMarkdown",
contexts: ["page", "selection"]
});
});
// create easy vars to use in the magic below
var stripped_elements = settings.get("strip_elements").split(', ');
var deleted_elements = settings.get("delete_elements").split(', ');
function callTab(tab) {
// Send a message to the active tab
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id, {"message": "wants_markdown"});
});
}
// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
callTab(tab);
});
// Called when the user clicks on the context menu action.
chrome.contextMenus.onClicked.addListener(function(info, tab) {
if (info.menuItemId === "getMarkdown") {
callTab(tab);
}
});
// check the message from content.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if (request.message === "result_exists") {
// parse incoming html for markdown
// request.content
var markdown = toMarkdown(request.content, {
// filter out stuff
converters: [{
// grab the settings
filter: stripped_elements,
replacement: function (innerHTML, node) { return innerHTML }
}, {
// don't include these in the final markdown
filter: deleted_elements,
replacement: function () { return '' }
}]
});
// create a ghost input to hold the fresh markdown
const textarea = document.createElement('textarea');
textarea.style.position = 'fixed';
textarea.style.opacity = 0;
// put da markdown in da box
textarea.value = markdown;
// put da box on the page
document.body.appendChild(textarea);
// select the newly appended text
textarea.select();
// copy it
document.execCommand('Copy');
// cover the tracks
document.body.removeChild(textarea);
} else {
alert("Oops! No content received.");
}
}
);