|
| 1 | +// User preferences change |
| 2 | +chrome.storage.onChanged.addListener((changes, areaName) => { |
| 3 | + const hasPreferencesChanged = areaName === "local" && changes.userPreferences; |
| 4 | + |
| 5 | + if (!hasPreferencesChanged) { |
| 6 | + return; |
| 7 | + } |
| 8 | + |
| 9 | + toggleAutoOpenPDFLinksOnCurrentTab(); |
| 10 | +}); |
| 11 | + |
| 12 | +// Current tab switch |
| 13 | +chrome.tabs.onActivated.addListener(() => { |
| 14 | + toggleAutoOpenPDFLinksOnCurrentTab(); |
| 15 | +}); |
| 16 | + |
| 17 | +// Current tab URL change |
| 18 | +chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => { |
| 19 | + if (changeInfo.status !== "complete") { |
| 20 | + return; |
| 21 | + } |
| 22 | + |
| 23 | + toggleAutoOpenPDFLinksOnCurrentTab(); |
| 24 | +}); |
| 25 | + |
| 26 | +function toggleAutoOpenPDFLinksOnCurrentTab() { |
| 27 | + chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => { |
| 28 | + const currentTab = tabs[0]; |
| 29 | + |
| 30 | + if (!currentTab || !currentTab.id || !currentTab.url) { |
| 31 | + return; |
| 32 | + } |
| 33 | + |
| 34 | + const isUnsupportedURL = |
| 35 | + currentTab.url.startsWith("chrome://") || |
| 36 | + currentTab.url.startsWith("edge://"); |
| 37 | + |
| 38 | + if (isUnsupportedURL) { |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + chrome.storage.local.get("userPreferences", ({ userPreferences }) => { |
| 43 | + const preferences = userPreferences ?? { autoOpen: false }; |
| 44 | + |
| 45 | + chrome.scripting.executeScript( |
| 46 | + { |
| 47 | + target: { tabId: currentTab.id }, |
| 48 | + files: ["./node_modules/@simplepdf/web-embed-pdf/dist/index.js"], |
| 49 | + }, |
| 50 | + () => { |
| 51 | + if (chrome.runtime.lastError) { |
| 52 | + return; |
| 53 | + } |
| 54 | + |
| 55 | + chrome.scripting.executeScript({ |
| 56 | + target: { tabId: currentTab.id }, |
| 57 | + func: (preferences) => { |
| 58 | + if (!window.simplePDF) { |
| 59 | + return; |
| 60 | + } |
| 61 | + |
| 62 | + window.simplePDF.setConfig({ |
| 63 | + autoOpen: preferences.autoOpen, |
| 64 | + companyIdentifier: "chrome", |
| 65 | + }); |
| 66 | + }, |
| 67 | + args: [preferences], |
| 68 | + }); |
| 69 | + }, |
| 70 | + ); |
| 71 | + }); |
| 72 | + }); |
| 73 | +} |
0 commit comments