e01.org

scripting.executeScript()

Injects a script into a target context. The script is run at documentidle by default.

Injects a script into a target context. The script is run at `document_idle` by default.

> [!NOTE]
> This method is available in Manifest V3 or higher in Chrome and Firefox 101. In Safari and Firefox 102+, this method is also available in Manifest V2.

To use this API you must have the `scripting` [permission](/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions) and permission for the target's URL, either explicitly as a [host permission](/docs/Mozilla/Add-ons/WebExtensions/manifest.json/permissions#host_permissions) or using the [`activeTab` permission](/docs/Mozilla/Add-ons/WebExtensions/activeTab_permission).

In Firefox and Safari, partial lack of host permissions can result in a successful execution (with the partial results in the resolved promise). In Chrome, any missing permission prevents any execution from happening (see [Issue 1325114](https://crbug.com/1325114)).

The scripts you inject are called [content scripts](/docs/Mozilla/Add-ons/WebExtensions/Content_scripts).

Extensions cannot run content scripts in [extension pages](/docs/Mozilla/Add-ons/WebExtensions/user_interface/Extension_pages). If an extension wants to run code in an extension page dynamically, it can include a script in the document. This script contains the code to run and registers a runtime.onMessage listener that implements a way to execute the code. The extension can then send a message to the listener to trigger the code's execution.

## Syntax

```js-nolint
let results = await browser.scripting.executeScript(
details // object
)
```

### Parameters

- `details`
- : An object describing the script to inject. It contains these properties:
- `args`
- : An array of arguments to carry into the function. This is only valid if the `func` parameter is specified. The arguments must be JSON-serializable.
- `files`
- : `array` of `string`. An array of path of the JS files to inject, relative to the extension's root directory. Exactly one of `files` and `func` must be specified.
- `func`
- : `function`. A JavaScript function to inject. This function is serialized and then deserialized for injection. This means that any bound parameters and execution context are lost. Exactly one of `files` and `func` must be specified.

The function is serialized from its source text, which must be a valid function expression. Use a function declaration, function expression, or arrow function. A function defined using [method syntax](/docs/Web/JavaScript/Reference/Functions/Method_definitions), such as `method() {}` in an object literal or class, doesn't serialize to a valid function expression, so it fails to run. Firefox returns a `SyntaxError` in the `error` property of the `InjectionResult`, while Chrome only reports the error in the target tab's console.
- `injectImmediately`
- : `boolean`. Whether the injection into the target is triggered as soon as possible, but not necessarily prior to page load.
- `target`
- : scripting.InjectionTarget. Details specifying the target to inject the script into.
- `world`
- : scripting.ExecutionWorld. The execution environment for a script to execute in.

### Return value

A Promise that fulfills with an array of `InjectionResult` objects, which represent the result of the injected script in every injected frame.

The promise is rejected if the injection fails, such as when the injection target is invalid. After injection has started, the promise fulfills even if the script fails to parse or throws an error. In that case, the `InjectionResult` for the frame contains the error in its `error` property rather than a `result`. To handle all failures, catch the rejected promise and check the `error` property of each result.

Each `InjectionResult` object has these properties:

- `documentId`
- : `string`. The document associated with the injection. See the [Work with documentId](/docs/Mozilla/Add-ons/WebExtensions/Work_with_documentId) article for more information.
- `frameId`
- : `number`. The frame ID associated with the injection.
- `result`
- : `any`. The result of the script execution.
- `error`
- : `any`. If an error occurs, contains the value the script threw or rejected with. Typically this is an error object with a message property but it could be any value (including primitives and undefined).

Chrome does not support the `error` property yet (see [Issue 1271527: Propagate errors from scripting.executeScript to InjectionResult](https://crbug.com/1271527)). As an alternative, runtime errors can be caught by wrapping the code to execute in a try-catch statement. Uncaught errors are also reported to the console of the target tab.

The result of a script is the value produced by the last evaluated statement. If the last statement produces a Promise, the result is the settled value of that Promise. This is similar to the results seen if you execute the script in the [Web Console](https://firefox-source-docs.mozilla.org/devtools-user/web_console/index.html) (excluding any `console.log()` output). For example, consider a script like this:

```js
let foo = "my result";
foo;
```

Here the results array contains the string `"my result"` as an element.

The script result must be a [structured cloneable](/docs/Web/API/Web_Workers_API/Structured_clone_algorithm) value in Firefox or a [JSON-serializable](/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#description) value in Chrome. The [Chrome incompatibilities](/docs/Mozilla/Add-ons/WebExtensions/Chrome_incompatibilities) article discusses this difference in more detail in the [Data cloning algorithm](/docs/Mozilla/Add-ons/WebExtensions/Chrome_incompatibilities#data_cloning_algorithm) section.

## Examples

This example executes a one-line code snippet in the active tab. It catches the promise rejection that occurs if the injection fails, and checks each result for an error from running the script:

```js
browser.action.onClicked.addListener(async (tab) => {
try {
const results = await browser.scripting.executeScript({
target: {
tabId: tab.id,
},
func: () => {
document.body.style.border = "5px solid green";
},
});
for (const { frameId, error } of results) {
if (error) {
console.error(`script failed in frame ${frameId}: ${error}`);
}
}
} catch (err) {
console.error(`failed to execute script: ${err}`);
}
});
```

This example executes a script from a file (packaged with the extension) called `"content-script.js"`. The script is executed in the active tab. The script is executed in subframes and the main document:

```js
browser.action.onClicked.addListener(async (tab) => {
try {
await browser.scripting.executeScript({
target: {
tabId: tab.id,
allFrames: true,
},
files: ["content-script.js"],
});
} catch (err) {
console.error(`failed to execute script: ${err}`);
}
});
```

## Browser compatibility

> [!NOTE]
> This API is based on Chromium's [`chrome.scripting`](https://developer.chrome.com/docs/extensions/reference/api/scripting#method-executeScript) API.

source: MDN Web Docs mirror · page

Cite this

"scripting.executeScript()". MDN Web Docs. CC BY-SA 2.5 (MDN). https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/scripting/executeScript

JSON record · API collection · citation policy