background.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. // Background script for the extension
  2. // Function to navigate a tab to a new URL
  3. function navigateTab(tabId, url) {
  4. return browser.tabs.update(tabId, { url: url });
  5. }
  6. // Listen for messages from popup or content scripts
  7. browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
  8. if (message.command === 'navigate') {
  9. if (message.tabId && message.url) {
  10. navigateTab(message.tabId, message.url)
  11. .then(() => sendResponse({ status: 'success' }))
  12. .catch(error => sendResponse({ status: 'error', message: error.message }));
  13. return true; // Required for async sendResponse
  14. }
  15. }
  16. });
  17. // Listen for tab updates to potentially inject scripts on certain URLs
  18. browser.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
  19. if (changeInfo.status === 'complete' && tab.url) {
  20. // Check if the URL matches your patterns and inject scripts as needed
  21. const urlPatterns = [
  22. /example\.com/,
  23. /another-site\.org/
  24. // Add more URL patterns as needed
  25. ];
  26. const shouldInject = urlPatterns.some(pattern => pattern.test(tab.url));
  27. if (shouldInject) {
  28. browser.tabs.executeScript(tabId, { file: '/content_scripts/content.js' })
  29. .catch(error => console.error('Error injecting script:', error));
  30. }
  31. }
  32. });