chrome.tabs.getSelected API¶
chrome.tabs.getSelected is a method within the Chrome Extension API used to retrieve the tab that is currently selected in a specified window^[600-developer__frontend__google__chrome-plugin-develop.md]. It is frequently used in extension development to identify the active tab context, allowing the extension to perform subsequent actions—such as script execution or DOM manipulation—on that specific tab^[600-developer__frontend__google__chrome-plugin-develop.md].
Method Signature¶
The method accepts two arguments^[600-developer__frontend__google__chrome-plugin-develop.md]:
windowId(optional): An integer specifying the ID of the window. Passingnullindicates the current window^[600-developer__frontend__google__chrome-plugin-develop.md].callback: A function that is invoked once the selected tab is retrieved^[600-developer__frontend__google__chrome-plugin-develop.md].
Callback Function¶
The callback function receives a Tab object containing details about the selected tab^[600-developer__frontend__google__chrome-plugin-develop.md]. The most relevant property for subsequent operations is tab.id, which serves as the unique identifier for the tab^[600-developer__frontend__google__chrome-plugin-develop.md].
Usage Pattern¶
The standard workflow involves calling the API, extracting the tab ID from the callback parameter, and using that ID to target the tab for further operations, such as injecting scripts^[600-developer__frontend__google__chrome-plugin-develop.md].
Example¶
The following example demonstrates retrieving the active tab and defining a helper function to execute scripts within it^[600-developer__frontend__google__chrome-plugin-develop.md].
chrome.tabs.getSelected(null, (tab) => {
var tabId = tab.id; // 获取当前tab的id
// 定义发送脚本函数
var sendUserNamePassword = (fun) => chrome.tabs.executeScript(tabId, fun);
// 后续可使用 sendUserNamePassword 在该tab中执行代码
});
Related Concepts¶
- [[Chrome Extension]]
- [[DOM Manipulation]]
Sources¶
^[600-developer__frontend__google__chrome-plugin-develop.md]