当打开多个选项卡并用脚本编写脚本时,如何使chrome.tabs.executeScript在相应的选项卡中运行代码? [英] When opening and scripting multiple tabs, how to make chrome.tabs.executeScript run code in the respective tab?

查看:325
本文介绍了当打开多个选项卡并用脚本编写脚本时,如何使chrome.tabs.executeScript在相应的选项卡中运行代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的扩展程序的内容脚本扫描某些页面上的供应商代码,并将它们与chrome.runtime.sendMessage一起发送到我的后台脚本,该脚本创建新的标签并在每个标签上执行一些代码.但是我遇到了所有代码仅在最后一个选项卡上运行的问题.

Content script of my extension scans some page for vendor codes and send them with chrome.runtime.sendMessage to my background script which creates new tabs and executes some code on each of them. But i faced the problem that all code runs only on the last tab.

我尝试将其放入异步/等待功能中,但没有成功.

I've tried to put it into some async/await function and it didn't work out.

chrome.runtime.onMessage.addListener(
  function (request, sender, sendResponse) {
      if (request.message === "open_new_tab") {
          for (let vCode of request.vCodes){
              chrome.tabs.create({url: "https://example.com/" + vCode}, function(){
              chrome.tabs.executeScript({code: "console.log(" + vCode + ")", runAt: 'document_end'});
          }); 
      }
  }
});

推荐答案

您没有指定标签页ID,因此executeScript使用活动标签页.由于API是异步的,因此当活动选项卡不是您过去创建的选项卡时,您的executeScript会在将来的某个未指定时间运行.

You didn't specify the tab id so executeScript uses the active tab. Since the API is asynchronous your executeScript is running at some unspecified time in the future when the active tab is not the tab you've created in the past.

只需重复使用提供给 chrome.tabs.create 的标签ID >的回调:

Simply reuse the tab id provided to chrome.tabs.create's callback:

chrome.runtime.onMessage.addListener(
  (request, sender, sendResponse) => {
    if (request.message === 'open_new_tab') {
      for (let vCode of request.vCodes) {
        chrome.tabs.create({url: 'https://example.com/' + vCode}, tab => {
          chrome.tabs.executeScript(tab.id, {code: `console.log(${vCode})`});
        });
      }
    }
  });

如果您只想打开一个选项卡并重新使用它以依次加载网站,则建议使用 Mozilla的WebExtension polyfill 和async/await:

If you want to open just one tab and reuse it to load the sites sequentially, I suggest utilizing Mozilla's WebExtension polyfill and async/await:

browser.runtime.onMessage.addListener(
  async (request, sender) => {
    if (request.message === 'open_new_tab') {
      let tab;
      for (const vCode of request.vCodes) {
        const url = 'https://example.com/' + vCode;
        tab = tab ?
          await browser.tabs.update(tab.id, {url}) :
          await browser.tabs.create({url});
        await browser.tabs.executeScript(tab.id, {code: `console.log(${vCode})`});
      }
    }
  });

这篇关于当打开多个选项卡并用脚本编写脚本时,如何使chrome.tabs.executeScript在相应的选项卡中运行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆