|
| 1 | +import type { Tabs, WebNavigation } from 'webextension-polyfill'; |
| 2 | +import { tabs, webNavigation, scripting } from 'webextension-polyfill'; |
| 3 | + |
| 4 | +export class ServiceWorker { |
| 5 | + private readonly urls: string[]; |
| 6 | + private readonly urlRegexs: RegExp[]; |
| 7 | + |
| 8 | + public constructor(urls: string[]) { |
| 9 | + this.urls = urls; |
| 10 | + this.urlRegexs = []; |
| 11 | + for (const url of this.urls) { |
| 12 | + this.urlRegexs.push(new RegExp(url, 'i')); |
| 13 | + } |
| 14 | + } |
| 15 | + |
| 16 | + public init(): void { |
| 17 | + tabs.onUpdated.addListener((tabId, changeInfo, tabInfo) => { |
| 18 | + void this.onTabUpdated(tabId, changeInfo, tabInfo); |
| 19 | + }); |
| 20 | + webNavigation.onCompleted.addListener((details) => { |
| 21 | + void this.onNavigationCompleted(details); |
| 22 | + }); |
| 23 | + } |
| 24 | + |
| 25 | + public async onTabUpdated( |
| 26 | + tabId: number, |
| 27 | + changeInfo: Tabs.OnUpdatedChangeInfoType, |
| 28 | + tabInfo: Tabs.Tab |
| 29 | + ): Promise<void> { |
| 30 | + if (changeInfo.url !== undefined && this.isJiraUrl(changeInfo.url)) { |
| 31 | + await this.injectContentScript(tabId); |
| 32 | + } |
| 33 | + } |
| 34 | + |
| 35 | + public async onNavigationCompleted( |
| 36 | + details: WebNavigation.OnCompletedDetailsType |
| 37 | + ): Promise<void> { |
| 38 | + if (details.url.length > 0 && this.isJiraUrl(details.url)) { |
| 39 | + await this.injectContentScript(details.tabId); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + private isJiraUrl(url: string): boolean { |
| 44 | + for (const x of this.urlRegexs) { |
| 45 | + if (x.test(url)) { |
| 46 | + return true; |
| 47 | + } |
| 48 | + } |
| 49 | + return false; |
| 50 | + } |
| 51 | + |
| 52 | + private async injectContentScript(tabId: number): Promise<void> { |
| 53 | + try { |
| 54 | + await scripting.executeScript({ |
| 55 | + target: { |
| 56 | + tabId, |
| 57 | + }, |
| 58 | + files: ['content.bundle.js'], |
| 59 | + }); |
| 60 | + } catch (error) { |
| 61 | + console.error(`Failed to inject content script: ${String(error)}`); |
| 62 | + } |
| 63 | + } |
| 64 | +} |
0 commit comments