Plug-in to control LED strips. scripting.executeScript dont work

32 Views Asked by At

I am a beginner programmer. I'm writing a plug-in to control LED strips from a browser, but I got stuck on a seemingly mundane thing. Namely, I am practicing data transfer between different browser tabs in order to transfer audio data from browser tabs with active sound to the tab with the LED control page from the cloud (yes, I know, a bit of an amateur approach, I should test the API of the LED strip manufacturer TUYA, but it will be easier for me). Coming to the point, I got stuck sending the plugin's background script to the active tab script. And scripts running on inactive tabs to a script running on the active tab. Or even from scripts between inactive tabs. My test code looks like this:

// background.js

// Function to send code to the console of the active card
function sendCodeToActiveAndInactiveTabs(code) {
   // Get all tabs in the active browser window
   chrome.tabs.query({ currentWindow: true }, function (tabs) {
     // Iterate through all tabs
     console.log("sensor");
     tabs.forEach(function (tab) {
       // Send code to the console for each tab
       if (tab.id) {
         chrome.scripting.executeScript({
           target: { tabId: tab.id },
           func: function (code) {
             eval(code);
           },
           args: [code],
         });
       } else {
         console.log("Invalid tab ID:", tab);
       }
     });
   });
}

// JavaScript code to send to the active tab's console
var codeToExecute = `
     console.log("Code executed in the console of the active card.");
     // Here you can put any code you want to execute in the active tab's console
     `;

// Call the function with the code to send to all cards
sendCodeToActiveAndInactiveTabs(codeToExecute);

Sorry for the comments in Polish. manifest.json:

{
   "manifest_version": 3,
   "name": "Chrome Plugin: First Tab ID",
   "version": "1.0",
   "permissions": [
     "tabs",
     "scripting",
     "activeTab",
     "contextMenus",
     "storage",
     "file://*/*"
   ],
   "host_permissions": [
     "https://developer.chrome.com/docs/extensions/develop/concepts/declare-permissions?hl=pl",
     "https://chat.openai.com/c/0382f384-5dbb-4f3c-b7cf-66dc4815c737"
   ],
   "optional_permissions": ["topSites"],
   "optional_host_permissions": ["https://*/*", "http://*/*"],
   "background": {
     "service_worker": "background.js"
   },
   "action": {
     "default_icon": {
       "16": "images/led.png",
       "48": "images/led.png",
       "128": "images/led.png"
     }
   }
}

Please help. I will be extremely grateful.

I got stuck sending the plugin's background script to the active tab script. And scripts running on inactive tabs to a script running on the active tab. Or even from scripts between inactive tabs. My test code looks like this:

0

There are 0 best solutions below