Robin focke
Robin focke

Reputation: 31

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';"
});

Upvotes: 1

Views: 980

Answers (1)

Aluan Haddad
Aluan Haddad

Reputation: 31873

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.

Upvotes: 2

Related Questions