at main 2.2 kB view raw
1// MV3 service worker to manage dynamic redirect rules based on user setting 2const DYNAMIC_RULE_ID = 1001; 3const STATIC_RULESET_ID = "ruleset_1"; 4 5async function getDestinationDomain() { 6 return new Promise((resolve) => { 7 chrome.storage.sync.get({ destinationDomain: "deer.social" }, (items) => { 8 resolve(items.destinationDomain || "deer.social"); 9 }); 10 }); 11} 12 13function buildDynamicRule(destinationDomain) { 14 return { 15 id: DYNAMIC_RULE_ID, 16 priority: 1000, 17 action: { 18 type: "redirect", 19 redirect: { 20 regexSubstitution: `https://${destinationDomain}/\\1`, 21 }, 22 }, 23 condition: { 24 regexFilter: "^https://bsky\\.app/(.*)$", 25 resourceTypes: ["main_frame", "sub_frame"], 26 }, 27 }; 28} 29 30async function applyDynamicRule() { 31 const destinationDomain = await getDestinationDomain(); 32 const rule = buildDynamicRule(destinationDomain); 33 await chrome.declarativeNetRequest.updateDynamicRules({ 34 removeRuleIds: [DYNAMIC_RULE_ID], 35 addRules: [rule], 36 }); 37} 38 39// Initialize on install/update and on startup 40chrome.runtime.onInstalled.addListener(async () => { 41 // Ensure a default is set 42 chrome.storage.sync.get( 43 { destinationDomain: "deer.social" }, 44 async (items) => { 45 if (!items.destinationDomain) { 46 chrome.storage.sync.set({ destinationDomain: "deer.social" }); 47 } 48 // Disable static ruleset if present in session 49 try { 50 await chrome.declarativeNetRequest.updateEnabledRulesets({ 51 disableRulesetIds: [STATIC_RULESET_ID], 52 }); 53 } catch (e) { 54 // ignore if not supported or not present 55 } 56 await applyDynamicRule(); 57 } 58 ); 59}); 60 61chrome.runtime.onStartup && 62 chrome.runtime.onStartup.addListener(() => { 63 // Also try to disable static ruleset on startup in case of stale state 64 chrome.declarativeNetRequest 65 .updateEnabledRulesets({ 66 disableRulesetIds: [STATIC_RULESET_ID], 67 }) 68 .catch(() => {}); 69 applyDynamicRule(); 70 }); 71 72// Update rule when the setting changes 73chrome.storage.onChanged.addListener((changes, area) => { 74 if (area === "sync" && changes.destinationDomain) { 75 applyDynamicRule(); 76 } 77});