-
Notifications
You must be signed in to change notification settings - Fork 1
/
global.js
100 lines (91 loc) · 2.66 KB
/
global.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
(function() {
// TODO collapse newlines for selections
"use strict";
var read = require("node-read");
var toMarkdown = require('to-markdown');
function getHtml(tab, cb) {
chrome.tabs.executeScript(null,
{code: "document.documentElement.innerHTML"},
cb);
}
// from http://stackoverflow.com/questions/2808368/decode-html-entities-in-javascript
function htmlDecode(input){
var e = document.createElement('div');
e.innerHTML = input;
return e.childNodes[0].nodeValue;
}
function savePage(tab) {
getHtml(tab, function(html) {
read(html[0], function(err, article, meta) {
if (! err) {
var markdown = toMarkdown(article.content, {
converters: [
{
filter: 'pre',
replacement: function(c, node) {
return '\n\n```\n' + node.innerText + '\n```\n\n';
}
},
{
filter: ['span', 'font', 'small'],
replacement: function(c) {
return c;
}
},
{
filter: ['div', 'figure', 'canvas'],
replacement: function(c) {
if (c.trim()) {
return '\n\n' + c + '\n\n';
}
return '\n\n';
}
},
{
filter: function (node) {
return node.nodeName === 'A' && !node.getAttribute('href');
},
replacement: function(c) {
return c;
}
}
]
});
saveToNv({
title: htmlDecode(article.title),
txt: 'Source: ' + tab.url + '\n\n' + markdown
});
}
});
});
}
function saveToNv(params) {
var base = "nvalt://make/";
var paramStr = Object.keys(params).map(function(k) {
var v = params[k];
return [encodeURIComponent(k), encodeURIComponent(v)].join('=');
}).join("&");
var url = [base, paramStr].join('?');
chrome.tabs.update(null, {url: url});
}
// Save whole page when extension button in toolbar is clicked
chrome.browserAction.onClicked.addListener(savePage);
// Context menu options
chrome.contextMenus.create({
"title": "Save note with page",
"contexts": ["page"],
"onclick": function(info, tab) {
savePage(tab);
}
});
chrome.contextMenus.create({
"title": "Save note with selected text",
"contexts": ["selection"],
"onclick": function(info, tab) {
saveToNv({
title: htmlDecode(tab.title),
txt: 'Source: ' + info.pageUrl + '\n\n' + info.selectionText
});
}
});
})();