从Chrome扩展程序中的内容脚本中获取"此"标签ID?

voi*_*ter 46 google-chrome-extension

从内容脚本中,是否可以访问该选项卡的ID?我想从内容脚本向后台页面发送一条消息,告诉我的扩展程序使用chrome.tabs.*api"使用此选项卡执行某些操作".需要一个TabID,当我的内容脚本可以简单地告诉它消息内容中的TabID时,在后台页面中做一堆逻辑以寻找一个TabID没有意义.

ser*_*erg 83

标签ID自动在MessageSender对象中传递:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    console.log("sent from tab.id=", sender.tab.id);
});
Run Code Online (Sandbox Code Playgroud)

  • @serg:如果我需要在消息响应处理器之外使用tabID怎么办? (14认同)
  • 嗯...对我来说,发件人是我的扩展程序页面,而不是活动页面 (3认同)

Aid*_*din 12

如果您想要tabId自己(在我的情况下在内容脚本中)而不需要" tabs"权限,则解决方法是让内容脚本向后台脚本发送虚拟消息,然后让后台脚本回复sender.tab.id内容脚本!

例如content.js:

chrome.runtime.sendMessage({ text: "what is my tab_id?" }, tabId => {
   console.log('My tabId is', tabId);
});
Run Code Online (Sandbox Code Playgroud)

并在background.js:

chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
    if (msg.text == "what is my tab_id?") {
        sendResponse({tab: sender.tab.id});
    }
});
Run Code Online (Sandbox Code Playgroud)

这是一个对我有用的愚蠢的解决方法.:)

PS.哦,如果您有tabs权限,那么您可以非常轻松地运行此异步查询:

chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
    var myTabId = tabs[0].id;
    chrome.tabs.sendMessage(myTabId, {text: "hi"}, function(response) {
        alert(response);
    });
});
Run Code Online (Sandbox Code Playgroud)

  • 不能在内容脚本中使用 chrome.tabs.query。它仅在后台和弹出脚本中可用。 (4认同)

Lou*_*ge9 10

如果您使用Ports进行双向长期连接,则回调中的第二个参数是Port对象,因此要访问选项卡ID,则:

chrome.runtime.onConnect.addListener(port => {
  if (port.name === "foo") {
    port.onMessage.addListener((msg, sendingPort) => {
      console.log("sent from tab.id=", sendingPort.sender.tab.id);
    });
  }
});
Run Code Online (Sandbox Code Playgroud)