chrome.scripting
-
Description
Use the
chrome.scripting
API to execute script in different contexts. -
Permissions
scripting
Manifest #
In order to use the chrome.scripting
API, you need to specify a
"manifest_version"
of 3
or higher and include the "scripting"
permission
in your manifest file.
{
"name": "Scripting Extension",
"manifest_version": 3,
"permissions": ["scripting"],
...
}
Usage #
You can use the chrome.scripting
API to inject JavaScript and CSS into
websites. This is similar to what you can do with
content scripts, but by using the chrome.scripting
API,
extensions can make decisions at runtime.
Injection targets #
You can use the target
parameter to specify a target to inject JavaScript or
CSS into.
The only required field is tabId
. By default, an injection will run in the
main frame of the specified tab.
const tabId = getTabId();
chrome.scripting.executeScript(
{
target: {tabId: tabId},
files: ['script.js'],
},
() => { ... });
To run in all frames of the specified tab, you can set the allFrames
boolean
to true
.
const tabId = getTabId();
chrome.scripting.executeScript(
{
target: {tabId: tabId, allFrames: true},
files: ['script.js'],
},
() => { ... });
You can also inject into specific frames of a tab by specifying individual frame IDs. For more information on frame IDs, see the webNavigation API.
const tabId = getTabId();
const frameIds = [frameId1, frameId2];
chrome.scripting.executeScript(
{
target: {tabId: tabId, frameIds: frameIds},
files: ['script.js'],
},
() => { ... });
You cannot specify both the frameIds
and allFrames
properties.
Injected code #
Extensions can specify the code to be injected either via an external file or a runtime variable.
Files #
Files are specified as strings that are paths relative to the extension's root
directory. The following code will inject the file script.js
into the main
frame of the tab.
const tabId = getTabId();
chrome.scripting.executeScript(
{
target: {tabId: tabId},
files: ['script.js'],
},
() => { ... });
Note: Currently, a maximum of a single file is supported.
Runtime functions #
When injecting JavaScript with scripting.executeScript()
, you can specify a
function to be executed instead of a file. This function should be a function
variable available to the current extension context.
function getTitle() {
return document.title;
}
const tabId = getTabId();
chrome.scripting.executeScript(
{
target: {tabId: tabId},
function: getTitle,
},
() => { ... });
This function will be executed in the context of injection target. However,
this will not carry over any of the current execution context of the function.
As such, bound parameters (including the this
object) and
externally-referenced variables will result in errors. For instance, the
following code will not work, and will throw a ReferenceError because color
is undefined when the function executes:
const color = getUserColor();
function changeBackgroundColor() {
document.body.style.backgroundColor = color;
}
const tabId = getTabId();
chrome.scripting.executeScript(
{
target: {tabId: tabId},
function: changeBackgroundColor,
},
() => { ... });
You can work around this by using the Storage API or by passing messages.
Runtime strings #
If injecting CSS within a page, you can also specify a string to be used in the
css
property. This option is only available for scripting.insertCSS()
; you
can't execute a string using scripting.executeScript()
.
const css = 'body { background-color = "red"; }';
const tabId = getTabId();
chrome.scripting.insertCSS(
{
target: {tabId: tabId},
css: css,
},
() => { ... });
Handling results #
The results of executing JavaScript are passed to the extension. A single result is included per-frame. The main frame is guaranteed to be the first index in the resulting array; all other frames are in a non-deterministic order.
function getTitle() {
return document.title;
}
const tabId = getTabId();
chrome.scripting.executeScript(
{
target: {tabId: tabId, allFrames: true},
function: getTitle,
},
(injectionResults) => {
for (const frameResult of injectionResults)
console.log('Frame Title: ' + frameResult.result);
});
scripting.insertCSS()
does not return any results.
Summary
-
Types
-
Methods
chrome.scripting.executeScript(injection: ScriptInjection, callback: function)
chrome.scripting.insertCSS(injection: CSSInjection, callback: function)
Types
CSSInjection
Properties
-
cssstring optional
A string containing the CSS to inject. Exactly one of
files
andcss
must be specified. -
filesstring[] optional
The path of the CSS files to inject, relative to the extension's root directory. NOTE: Currently a maximum of one file is supported. Exactly one of
files
andcss
must be specified. -
originStyleOrigin optional
The style origin for the injection. Defaults to
'AUTHOR'
. -
target
Details specifying the target into which to insert the CSS.
InjectionResult
Properties
-
resultany optional
The result of the script execution.
InjectionTarget
Properties
-
allFramesboolean optional
Whether the script should inject into all frames within the tab. Defaults to false. This must not be true if
frameIds
is specified. -
frameIdsnumber[] optional
-
tabIdnumber
The ID of the tab into which to inject.
ScriptInjection
Properties
-
filesstring[] optional
The path of the JS files to inject, relative to the extension's root directory. NOTE: Currently a maximum of one file is supported. Exactly one of
files
andfunction
must be specified. -
functionfunction optional
A JavaScript function to inject. This function will be serialized, and then deserialized for injection. This means that any bound parameters and execution context will be lost. Exactly one of
files
andfunction
must be specified.The function function looks like this:
function() => {...}
-
target
Details specifying the target into which to inject the script.
StyleOrigin
The origin for a style change. See
Enum
"AUTHOR"
,
or
"USER"
Methods
executeScript
chrome.scripting.executeScript(injection:
ScriptInjection, callback:
function)
Injects a script into a target context. The script will be run at
document_end
.
Parameters
-
injection
The details of the script which to inject.
-
callbackfunction
Invoked upon completion of the injection. The resulting array contains the result of execution for each frame.
The callback parameter should be a function that looks like this:
(results: InjectionResult[]) => {...}
-
results
-
insertCSS
chrome.scripting.insertCSS(injection:
CSSInjection, callback:
function)
Inserts a CSS stylesheet into a target context.
Parameters
-
injection
The details of the styles to insert.
-
callbackfunction
Invoked upon completion of the insertion.
The callback parameter should be a function that looks like this:
() => {...}