javascript - 从 Chrome 扩展程序中的内容脚本获取 "this"选项卡 ID?

标签 javascript google-chrome-extension

从内容脚本中,是否可以访问该选项卡的id

我想从内容脚本向后台页面发送一条消息,告诉我的扩展程序使用 chrome.tabs.* API“使用此选项卡执行某些操作”。

需要一个 tabID,当我的内容脚本可以简单地告诉它时,在后台页面中执行一堆逻辑来寻找 tabID 是没有意义的消息内容中的 tabID

最佳答案

选项卡 ID 会自动传入 MessageSender 内部对象:

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

注:根据docs ,此属性并不总是可用:

This property will only be present when the connection was opened from a tab (including content scripts), and only if the receiver is an extension, not an app.

关于javascript - 从 Chrome 扩展程序中的内容脚本获取 "this"选项卡 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6202953/

相关文章:

javascript - Chrome 扩展内容脚本 - .click() 不起作用

javascript - HTML5 phonegap webapp 在 safari 或其他原生应用程序中打开链接

javascript - 使用 AJAX 返回 javascript

JavaScript OnChange 仅在 Internet Explorer 中不会触发

google-chrome - Chrome 扩展程序 - 内容脚本匹配是否仅限于权限?

javascript - 如何检测是否在我的页面中注入(inject)了不需要的 chrome 内容脚本?

javascript - 不同的babel环境配置

javascript - jQuery 在 Chrome 下查找错误的元素

google-chrome - 在 chrome 扩展中捕获元素图像(缩放失败)

google-chrome - 我可以使用 Google Chrome 的 API 更改 UI 吗?