chrome.scripting.executeScript Fails with “Tab Not Found” Error After Creating a New Window in Chrome Extension

I’m developing a Chrome extension and encountering an issue with executing a script in a newly created tab. Here’s what I’m trying to achieve:

On a button click, I use chrome.windows.create api to open a new popup window. In window I am opening an external webpage.

      // Create the window at the bottom-right corner
      chrome.windows.create({
          url: "https://localhost/index.html", // Replace with your HTML file
          focused: true,
        },
        function (window) {

          tabId = window.id; // Store the ID of the created window

          console.log("Window created at bottom-right corner.", tabId);
          chrome.storage.local.set({
              tabId: tabId
            },
            function () {
              console.log("Popup window ID stored:", tabId);
            }
          );

        });

I am trying to send a message from background.js to https://localhost/index.html using following code


     // This part Working Successfully
    `chrome.windows.update(tabId, {
        focused: true,
     });

`
     chrome.scripting.executeScript({
        target: {
          tabId: tabId
        },
        func: () => {
          window.postMessage(message, '*');
        }
      }, () => {
        if (chrome.runtime.lastError) {
          console.error(`Script execution failed: ${chrome.runtime.lastError.message}`);
        } else {
          console.log('Message sent to the new window');
        }
     });

chrome.scripting.executeScript, is failing with Script execution failed. tab not found for id : XXXX error.

  1. I have included necessary permission e.g. tabs, activetab, scripting in v3 manifest file.
  2. I checked if the tab is fully loaded before attempting to execute the script.

I was wondering why am I receiving the “Tab Not Found” error, and how can I ensure that chrome.scripting.executeScript works correctly with newly created window?

My goal is to send message to https://localshot/index.html.