forked from 027xiguapi/code-box
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tools.ts
77 lines (65 loc) · 2.01 KB
/
tools.ts
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
import dayjs from "dayjs"
import { saveAs } from "file-saver"
import { sendToBackground } from "@plasmohq/messaging"
export function addCss(code) {
const style = document.createElement("style")
const css = document.createTextNode(code)
style.appendChild(css)
document.head.appendChild(style)
}
export function addJs(code) {
const script = document.createElement("script")
// const js = document.createTextNode(`(()=>{${code}})()`)
const js = document.createTextNode(code)
script.appendChild(js)
document.head.appendChild(script)
}
export function setIcon(active: boolean) {
sendToBackground({
name: "icon",
body: {
active: active
}
})
}
export function saveTxt(txt: string, filename?: string) {
if (txt) {
const blob = new Blob([txt], { type: "text/plain;charset=utf-8" })
filename = filename || "CodeBox-page"
saveAs(blob, `${filename}-${dayjs().format("YYYY-MM-DD HH:mm:ss")}.txt`)
}
}
export function saveHtml(dom: Element, filename?: string) {
if (dom) {
const htmlContent = dom.outerHTML
const blob = new Blob([htmlContent], { type: "text/html;charset=utf-8" })
filename = filename || "CodeBox-page"
saveAs(blob, `${filename}-${dayjs().format("YYYY-MM-DD HH:mm:ss")}.html`)
}
}
export function saveMarkdown(markdown: string, filename?: string) {
if (markdown) {
const blob = new Blob([markdown], { type: "text/markdown;charset=utf-8" })
filename = filename || "CodeBox-page"
saveAs(blob, `${filename}-${dayjs().format("YYYY-MM-DD HH:mm:ss")}.md`)
}
}
export function i18n(key: string) {
return chrome.i18n.getMessage(key)
}
export function getMetaContentByProperty(metaProperty: string) {
const metas = document.getElementsByTagName("meta")
for (let i = 0; i < metas.length; i++) {
if (metas[i].getAttribute("property") === metaProperty) {
return metas[i].getAttribute("content")
}
}
return ""
}
export function isValidUrl(urlString: string) {
try {
return Boolean(new URL(urlString))
} catch (e) {
return false
}
}