background.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Store connections between devtools and tabs
  2. const connections = new Map();
  3. // Listen for connections from the devtools panel
  4. chrome.runtime.onConnect.addListener(port => {
  5. let tabId;
  6. // Listen for messages from the devtools panel
  7. port.onMessage.addListener(message => {
  8. if (message.name === 'init') {
  9. tabId = message.tabId;
  10. connections.set(tabId, port);
  11. console.log('DevTools connection initialized for tab:', tabId);
  12. } else if ((message.name === 'traverse' || message.name === 'reload-scene') && tabId) {
  13. console.log('Background: Forwarding', message.name, 'message to tab', tabId, 'with UUID:', message.uuid);
  14. // Forward traverse or reload request to content script
  15. chrome.tabs.sendMessage(tabId, message);
  16. }
  17. });
  18. // Clean up when devtools is closed
  19. port.onDisconnect.addListener(() => {
  20. if (tabId) {
  21. connections.delete(tabId);
  22. console.log('DevTools connection closed for tab:', tabId);
  23. }
  24. });
  25. });
  26. // Listen for messages from the content script
  27. chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  28. if (sender.tab) {
  29. const tabId = sender.tab.id;
  30. const port = connections.get(tabId);
  31. if (port) {
  32. // Forward the message to the devtools panel
  33. try {
  34. port.postMessage(message);
  35. // Send immediate response to avoid "message channel closed" error
  36. sendResponse({ received: true });
  37. } catch (e) {
  38. console.error('Error posting message to devtools:', e);
  39. // If the port is broken, clean up the connection
  40. connections.delete(tabId);
  41. }
  42. }
  43. }
  44. return false; // Return false to indicate synchronous handling
  45. });
  46. // Listen for page navigation events
  47. chrome.webNavigation.onCommitted.addListener(details => {
  48. const { tabId, frameId } = details;
  49. const port = connections.get(tabId);
  50. if (port) {
  51. console.log('Navigation in tab:', tabId, 'frame:', frameId);
  52. port.postMessage({
  53. id: 'three-devtools',
  54. type: 'committed',
  55. frameId: frameId
  56. });
  57. }
  58. });
粤ICP备19079148号