> Portal Navigation:
>
> - Append `.md` to any URL under `https://dev.wix.com/docs/` to get its markdown version.
> - Pages are either content pages (article or reference text) or menu pages (a list of links to child pages).
> - To get a menu page, truncate any URL to a parent path and append `.md` (e.g. `https://dev.wix.com/docs/sdk.md`, `https://dev.wix.com/docs/sdk/core-modules.md`).
> - Top-level index of all portals: https://dev.wix.com/docs/llms.txt
> - Full concatenated docs: https://dev.wix.com/docs/llms-full.txt
## Resource: Add an Embedded Script Extension to a Self-hosted App
## Article: Add an Embedded Script Extension to a Self-hosted App
## Article Link: https://dev.wix.com/docs/build-apps/develop-your-app/frameworks/self-hosting/supported-extensions/site-extensions/embedded-scripts/add-an-embedded-script-extension-to-a-self-hosted-app.md
## Article Content:
# Add an Embedded Script Extension to a Self-Hosted App
An embedded script is an app extension that injects an HTML code fragment into the DOM of your users' sites. Unlike other extensions, embedded scripts aren't fully configured by default during app installation and an extra step is required to embed the code fragment.
An example of an HTML code fragment is:
```javascript
```
This article explains how to:
1. [Add an embedded script extension](#step-1--add-an-embedded-script-extension).
1. [Embed the script upon app installation](#step-2--embed-the-script-upon-app-installation).
1. [Test the embedded script on a demo site](#step-3--test-your-script).
After following these steps, your app will have an embedded script extension that injects its HTML code fragment into the DOM of every page of your users' sites.
## Step 1 | Add an embedded script extension
1. Create a new app, or select an existing app from the [Custom Apps page](https://manage.wix.com/account/custom-apps) in your Wix Studio workspace.
1. Go to [**Extensions**](https://manage.wix.com/app-selector?title=Select+an+App&primaryButtonText=Select+Site&actionUrl=https%3A%2F%2Fdev.wix.com%2Fapps%2F%7BappId%7D%2Fextensions) and click **+Create Extension**.
1. Find **Embedded Script**.
1. Click **Create**.
1. Name your extension. The name can only contain letters and the hyphen (-) character.
1. Select a **Script Type**:
- **Essential:** Enables site visitors to move around the website and use essential features like secure and private areas crucial to the functioning of the site.
- **Functional:** Remembers choices site visitors make to improve their experience. For example, language.
- **Analytics:** Helps site owners understand how visitors use their website by providing statistics, such as which pages they visit, and by identifying errors and performance issues.
- **Advertising:** Lets site owners collect information to help market their products, such as data on the impact of marketing campaigns or re-targeted advertising.
Site owners can allow visitors to choose whether to opt out of cookies and 3rd-party scripts. Sites check the script type against the visitor's consent policy to determine whether to run the script.
> **Note:** An embedded script can't be saved without a type. If your script falls into more than 1 type, choose the option closest to the bottom of the list above. For example, if your script has **Advertising** and **Analytics** aspects, choose **Advertising** as its type. It's unlikely that you'll need to mark it as **Essential**. For more information, see our [guidelines for embedded scripts](https://dev.wix.com/docs/build-apps/launch-your-app/legal-and-security/gdpr-compliance/implement-cookie-consent-requirements.md).
1. Write the custom code to embed, including any relevant [dynamic parameters](https://dev.wix.com/docs/build-apps/develop-your-app/extensions/site-extensions/embedded-scripts/about-embedded-scripts.md#dynamic-parameters).
- For efficiency, load the code from an external source so that you can edit the script on the external platform instead of within the extension. This ensures that changes, except for changes made to dynamic parameters, are automatically reflected across all app versions without needing individual reviews.
- Your script may not run until after the DOM has fully loaded. Therefore, you should check whether the DOM has loaded before running your code.
Example: Use the DOMContentLoaded event to check if the DOM has loaded
```js
if (document.readyState === "loading") {
// DOM has not finished loading
document.addEventListener("DOMContentLoaded", runMyCode);
} else {
// DOM has loaded
runMyCode();
}
```
- To call APIs using the [Wix JavaScript SDK](https://dev.wix.com/docs/sdk.md), you need to [authenticate using the Wix Client](https://dev.wix.com/docs/build-apps/develop-your-app/frameworks/self-hosting/supported-extensions/site-extensions/embedded-scripts/authenticate-using-the-wix-client-in-self-hosted-embedded-script-extensions.md).
1. [Set up a dashboard page](https://dev.wix.com/docs/build-apps/develop-your-app/extensions/dashboard-extensions/dashboard-pages/about-dashboard-page-extensions.md) in the [app dashboard](https://manage.wix.com/account/custom-apps) for users to set up and customize the embedded script.
## Step 2 | Embed the script upon app installation
Your app needs to make a POST request to enable the embedded script in 2 cases:
1. Register to the [App Instance Installed](https://dev.wix.com/docs/rest/app-management/app-instance/app-instance-installed.md) webhook. For guidance, see [Handle Events With Webhooks](https://dev.wix.com/docs/build-apps/develop-your-app/frameworks/self-hosting/webhooks/handle-events-with-webhooks-for-self-hosting-using-the-java-script-sdk.md).
1. Use the instance ID received from the webhook to [create an access token](https://dev.wix.com/docs/rest/app-management/oauth-2/create-access-token.md). For more information, see [Authenticate Using OAuth](https://dev.wix.com/docs/build-apps/develop-your-app/access/authentication/authenticate-using-oauth.md).
1. Upon receipt of the webhook, make a POST request to the [Embed Script endpoint](https://dev.wix.com/docs/api-reference/app-management/embedded-scripts/embed-script.md) with the access token provided in the `Authorization` header of the request:
* If your script includes [dynamic parameters](https://dev.wix.com/docs/build-apps/develop-your-app/extensions/site-extensions/embedded-scripts/about-embedded-scripts.md#dynamic-parameters), include them in the request body under the `parameters` key:
```json
{
"properties": {
"parameters": {
"": "",
"": ""
}
}
}
```
* If your script doesn't include [dynamic parameters](https://dev.wix.com/docs/build-apps/develop-your-app/extensions/site-extensions/embedded-scripts/about-embedded-scripts.md#dynamic-parameters), make the call with the following request body:
```json
{
"properties": {}
}
```
1. (Optional) If your app includes multiple embedded scripts, each request must specify the `componentId` in the request body sent to the [Embed Script endpoint](https://dev.wix.com/docs/api-reference/app-management/embedded-scripts/embed-script.md):
```json
{
"properties": {
"parameters": {
"": ""
}
},
"componentId": ""
}
```
The `componentId` can be found within the URL of the embedded script page in your [app's dashboard](https://manage.wix.com/account/custom-apps):

__Warning:__ If your app only has 1 embedded script, don't pass the `componentId` in the request body. This action could lead to your app breaking in production. The `componentId` is only relevant for apps with more than 1 embedded script.
Here's some example code that uses the [JavaScript SDK](https://dev.wix.com/docs/sdk.md) to embed a script. The SDK requires the use of the [`embedScript()`](https://dev.wix.com/docs/sdk/backend-modules/app-management/embedded-scripts/embed-script.md) method:
```js
import { createClient, AppStrategy } from "@wix/sdk";
import { embeddedScripts } from "@wix/app-management";
// Get a Wix client bound to the refresh token
const myClient = createClient({
auth: AppStrategy({
appId: "YOUR_APP_ID",
appSecret: "YOUR_APP_SECRET",
refreshToken,
}),
modules: {
embeddedScripts,
},
});
async function embedCustomScript() {
const scriptProperties = {
script: ``
};
try {
await myClient.embeddedScripts.embedScript({
properties: scriptProperties,
});
console.log("Script embedded successfully.");
} catch (error) {
console.error("Failed to embed script:", error);
}
}
// Call this function upon app installation
embedCustomScript();
```
Now your embedded script will be injected into a site upon app installation.
## Step 3 | Test your script
To test your embedded script:
1. Install your app on a site.
1. Visit the test site where the app is installed. Inspect the site and check that the script appears in the site code. You can see the script in the network tab by filtering for "tags".
__Tip:__ If you don't see the script on the site, go to **App > Manage Apps** page within the site dashboard, and check that the script isn't disabled.
1. If you used dynamic parameters, check that they exist in the script as expected.
For more information on testing, see [App Checks and Testing Guide](https://dev.wix.com/docs/build-apps/launch-your-app/app-distribution/app-checks-and-testing-guide.md).
## See also
* [About Embedded Scripts](https://dev.wix.com/docs/build-apps/develop-your-app/extensions/site-extensions/embedded-scripts/about-embedded-scripts.md)
* [About Embedded Scripts and the Wix CLI](https://dev.wix.com/docs/wix-cli/guides/extensions/site-extensions/embedded-scripts/about-embedded-scripts.md)
* [Add an Embedded Script Extension with the Wix CLI](https://dev.wix.com/docs/wix-cli/guides/extensions/site-extensions/embedded-scripts/add-an-embedded-script-extension.md)