Skip to content

Chrome tabs.executeScript API

chrome.tabs.executeScript is a method used within Chrome Extension Development to inject and execute JavaScript code into the context of a specific tab in the browser.^[600-developer-frontend-google-chrome-plugin-develop.md]

Syntax and Parameters

The API method accepts a tab ID as its first argument and an object defining the script details as the second.^[600-developer-frontend-google-chrome-plugin-develop.md] This object must contain a code property holding the JavaScript string to be executed.^[600-developer-frontend-google-chrome-plugin-develop.md]

The target tab is typically identified using chrome.tabs.getSelected, which retrieves the active tab object, allowing the extension to extract the specific tab.id required for the injection.^[600-developer-frontend-google-chrome-plugin-develop.md]

Usage

This function allows a script running in the extension's background or popup context (such as popup.js) to manipulate the DOM of the active web page.^[600-developer-frontend-google-chrome-plugin-develop.md] Common use cases include programmatically setting input field values and triggering click events on elements, which enables tasks like automated form filling or login.^[600-developer-frontend-google-chrome-plugin-develop.md]

Example

The following example demonstrates how to define a wrapper function for the API and use it to inject code that fills in a username and password and submits a form^[600-developer-frontend-google-chrome-plugin-develop.md]:

chrome.tabs.getSelected(null, (tab) => {
    var tabId = tab.id;
    var sendUserNamePassword = (fun) => chrome.tabs.executeScript(tabId, fun);

    document.getElementById('myPay').addEventListener('click', () => {
        "use strict";
        sendUserNamePassword({
            code: 'document.getElementById("name").value = "user"; document.getElementById("pwd").value = "password"; document.getElementById("AccountDoLoginBtn").click();'
        })
    });
});
  • [[Chrome Extension Manifest]]
  • [[Content Scripts]]
  • [[DOM Manipulation]]

Sources

  • 600-developer-frontend-google-chrome-plugin-develop.md