-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathbackground.js
83 lines (75 loc) · 2.35 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
80
81
82
83
import { formatFileName, composeText } from "./utils.js";
function extractText() {
const title = document.title;
const url = window.location.href;
return {
title: title,
url: url,
text: window.getSelection().toString().trim() || document.body.innerText
}
};
function copyText() {
function composeText(title, url, body) {
return title + '\n' + url + "\n\n" + body;
}
let allText = composeText(document.title, window.location.href, window.getSelection().toString().trim() || document.body.innerText);
navigator.clipboard.writeText(allText);
return allText;
};
function executeCommand(command, tab){
if(tab.url.indexOf("chrome://") === -1){
if(command === 'download-text'){
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: extractText,
}).then(async (r) => {
const res = r[0].result
const allText = composeText(res.title , res.url, res.text)
chrome.downloads.download({
url: 'data:text/plain;charset=utf-8,' + encodeURIComponent(allText),
filename: formatFileName(res.title),
saveAs: true
});
});
} else if(command === 'copy-text'){
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: copyText,
}).then(async (r) => {
/*
const allText = r[0].result
console.log("allText", allText);
*/
});
}
}
};
chrome.action.onClicked.addListener( (tab) => {
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: extractText,
}).then(async (r) => {
const res = r[0].result
let resTab = await chrome.tabs.create({url: chrome.runtime.getURL("plain-text.html?t=" + encodeURIComponent(res.title) +"&u=" + encodeURIComponent(res.url) +"&tx=" + encodeURIComponent(res.text))});
//console.log("resTab", resTab);
});
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
executeCommand(info.menuItemId, tab)
});
chrome.commands.onCommand.addListener((command, tab) => {
console.log(`Command: ${command}, Tab: ${tab.url}`);
executeCommand(command, tab)
});
chrome.runtime.onInstalled.addListener(function (a,b,c) {
chrome.contextMenus.create({
title: 'Copy',
id: 'copy-text',
contexts: ['all'],
});
chrome.contextMenus.create({
title: 'Download',
id: 'download-text',
contexts: ['all'],
});
});