-
Notifications
You must be signed in to change notification settings - Fork 1
/
background.ts
97 lines (80 loc) · 2.6 KB
/
background.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import { Storage } from "@plasmohq/storage"
import type { UrlMatch, Redirect } from "~types"
import Logger from "~lib/logger"
const extensionName = "dossi"
const storage = new Storage()
const logger = new Logger("dossi")
const uninstallUrl = "https://www.dossi.dev/uninstall"
const installUrl = "https://www.dossi.dev/success-install"
logger.info(`👋 Initializing ${extensionName}.`)
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
if (request.action === "openOptionsPage") {
chrome.runtime.openOptionsPage()
}
})
chrome.tabs.query({ url: process.env.PLASMO_PUBLIC_MATCHES }, function (tabs) {
for (let tab of tabs) {
chrome.tabs.onUpdated.addListener((tabId, changeInfo, updatedTab) => {
if (tabId === tab.id && changeInfo.status === "complete") {
try {
chrome.tabs.sendMessage(tabId, {
type: "URL_CHANGE",
})
} catch (error) {
logger.error(error)
}
}
})
}
})
const patterns = [
{
originAndPathMatches: `^https://github\.com/[a-zA-Z0-9\-_]+/[a-zA-Z0-9\-_]+/discussions/[0-9]+$`,
},
{
originAndPathMatches: `^https://github\.com/[a-zA-Z0-9\-_]+/[a-zA-Z0-9\-_]+/issues/[0-9]+$`,
},
{
originAndPathMatches: `^https://github\.com/[a-zA-Z0-9\-_]+/[a-zA-Z0-9\-_]+/pulls/[0-9]+$`,
},
{
originAndPathMatches: `^https://github\.com/[a-zA-Z0-9\-_]+/[a-zA-Z0-9\-_]+$`,
},
{ originAndPathMatches: `^https://github\.com/[a-zA-Z0-9\-_]+$` },
]
patterns.forEach((pattern, pos) => {
chrome.webNavigation.onBeforeNavigate.addListener(
async (details) => {
await storage.set("from", { url: details.url, pos } as UrlMatch)
},
{ url: [pattern] }
)
chrome.webNavigation.onCommitted.addListener(
async (details) => {
await storage.remove("redirect")
if (details.transitionQualifiers.includes("server_redirect")) {
logger.log("server_redirect detected.")
let from: UrlMatch | null = await storage.get<UrlMatch>("from")
if (!from) {
return
}
const to = { url: details.url, pos } as UrlMatch
if (from && to && from?.url !== to?.url && from?.pos == to?.pos) {
await storage.set("redirect", {
from: from?.url,
to: to?.url,
} as Redirect)
// remove from storage
await storage.remove("from")
}
}
},
{ url: [pattern] }
)
})
chrome.runtime.onInstalled.addListener(async (details) => {
chrome.runtime.setUninstallURL(uninstallUrl)
if (details.reason === "install") {
chrome.tabs.create({ url: installUrl })
}
})