1

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.