-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogseq.user.js
98 lines (85 loc) · 2.51 KB
/
logseq.user.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
// ==UserScript==
// @name New script - logseq.com
// @namespace Violentmonkey Scripts
// @match https://logseq.com/*
// @grant GM_xmlhttpRequest
// @version 1.0
// @inject-into page
// @description 4/28/2021, 1:24:23 PM
// ==/UserScript==
unsafeWindow.fetchNoCors = (url) => new Promise((resolve, reject) => GM_xmlhttpRequest({
url,
method: 'GET',
onabort: () => reject(),
onerror: () => reject(),
onloadend: (res) => resolve({ async text() { return res.responseText; } }),
}));
// pages to markdown
var scr = unsafeWindow.document.createElement('script');
scr.src = "https://unpkg.com/turndown/dist/turndown.js";
unsafeWindow.document.head.appendChild(scr);
scr = unsafeWindow.document.createElement('script');
scr.src = "https://cdn.jsdelivr.net/npm/@mozilla/[email protected]/Readability.js";
unsafeWindow.document.head.appendChild(scr);
unsafeWindow.pageToMarkdown = async function(pageUrl) {
function createDoc(htmlStr) {
var doc = document.implementation.createHTMLDocument('');
doc.open();
doc.write(htmlStr);
doc.close();
return doc;
}
try {
let {text} = await this.fetchNoCors(pageUrl);
let result = await text();
let ret = {
title: '',
md: '',
excerpt: ''
}
var turndownService = new TurndownService();
turndownService.remove('script');
turndownService.remove('footer');
turndownService.remove('style');
turndownService.addRule('a', {
filter: ['a'],
replacement: function (content, node, options) {
if (!node.href) {
return `[${content}]`;
}
let href = node.getAttribute('href');
let url = new URL(href, pageUrl);
return `[${content}](${url.toString()})`;
}
});
turndownService.addRule('iframe', {
filter: ['iframe'],
replacement: function (content, node, options) {
if (!node.src) {
return '';
}
let src = node.getAttribute('src');
let url = new URL(src, pageUrl);
return `_iframe to_: [${url.toString()}](${url.toString()})`;
}
});
let doc = createDoc(result);
var article = new Readability(doc).parse();
var {
title,
content,
textContent,
length,
excerpt,
byline,
dir,
} = article;
var markdown = turndownService.turndown(content);
ret.title = title;
ret.md = markdown;
return ret;
} catch(err) {
console.error('Error fetching page', err);
alert('error importing page');
}
}