简体   繁体   English

Chrome 扩展在新标签页中运行 js

[英]Chrome extension run js in new tab

My popup.js:我的popup.js:

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

How i can run this js in the new created tab?我如何在新创建的选项卡中运行这个 js?

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

When you create a tab, you can pass a callback function that receives the newly created tab for manipulation.创建选项卡时,您可以传递一个回调 function 接收新创建的选项卡进行操作。 This tab has an id which is 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.此选项卡有一个id ,用于指定脚本应在哪个选项卡中执行。除非您指定选项卡 ID,否则脚本将在当前选项卡中执行,而不是在新创建的选项卡中执行。 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.有关详细信息,请参阅Chrome 选项卡 API 文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM