content.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. // Wrap everything in an IIFE to avoid global scope pollution
  2. (() => {
  3. // Only initialize if we haven't already
  4. if (window.__nanoTabObserver) {
  5. return;
  6. }
  7. // Function to generate a fallback ID when tab ID is unavailable
  8. function generateFallbackId() {
  9. return `fallback-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
  10. }
  11. // Function to ensure ID is assigned
  12. function ensureTabId() {
  13. if (!document.body.hasAttribute('data-nano-tab-id')) {
  14. // Get tab ID from chrome runtime
  15. chrome.runtime.sendMessage({ type: 'GET_TAB_ID' }, (response) => {
  16. let uniqueId;
  17. if (response?.tabId) {
  18. uniqueId = `nano-tab-${response.tabId}`;
  19. } else {
  20. uniqueId = generateFallbackId();
  21. console.warn('Using fallback ID: Tab ID was unavailable');
  22. }
  23. document.body.setAttribute('data-nano-tab-id', uniqueId);
  24. });
  25. }
  26. return document.body.getAttribute('data-nano-tab-id');
  27. }
  28. // Run immediately when script loads
  29. ensureTabId();
  30. // Create observer and store it in a window property to prevent duplicate initialization
  31. window.__nanoTabObserver = new MutationObserver(ensureTabId);
  32. window.__nanoTabObserver.observe(document.body, {
  33. attributes: true
  34. });
  35. })();