'Chrome extension run js in new tab

My popup.js:

chrome.tabs.create({ url: "https://mywebsite.com" })

How i can run this js in the new created tab?

chrome.tabs.executeScript(null, {
  code: "document.getElementById('test').value='test';"
});


Solution 1:[1]

When you create a tab, you can pass a callback function that receives the newly created tab for manipulation. This tab has an id which can be used to specify which tab the script should be executed in. Unless you specify a tab ID, the script will be executed in the current tab instead of the newly created one. Therefore what you want is roughly

chrome.tabs.create({ url: "https://mywebsite.com" }, tab => {
  chrome.tabs.executeScript(tab.id, {
    code: "document.getElementById('test').value='test';"
  });
});

Or more elegantly

function createTab(options) {
  return new Promise(resolve => {
    chrome.tabs.create(options, resolve);
  });
}

async function main() {
  const tab = await createTab({ url: "https://mywebsite.com" });

  chrome.tabs.executeScript(tab.id, {
    code: "document.getElementById('test').value='test';"
  });
}

main();

See the Chrome Tab API documentation for details.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1