# Embedding

UI Bakery self-hosted can be easily embedded in other web applications and pages. It is also possible to setup two-way communication between an embedded app and the website the app is embedded in.

Before you proceed, make sure that `UI_BAKERY_EMBEDDED_ENABLE_ACTIONS_EXECUTION=true` variable is enabled in your instance.

1. Embed UI Bakery in an iframe where `src` is a link to an Embedded UI Bakery application (e.g. `https://custom-uibakery.com/share/SKDUFYUDF`)

```html
<script src="https://custom-uibakery.com/uibakery-embedded.js"></script>
<iframe width="100%" height="50%" id="uibakery" src="https://custom-uibakery.com/share/SKDUFYUDF"></iframe>
```

2. Add a script tag to the page where UI Bakery app is embedded to communicate with internal app actions:

```html
<input type="number" value="10" />
<button>Execute Action</button>

<script>
  const bakery = UIBakery('#uibakery');
  bakery.onReady(() => {
    document.querySelector('button').addEventListener('click', () => {
      const limit = parseInt(document.querySelector('input').value, 10);

      // execute UI Bakery action with {{params}} = { limit: 10 }
      bakery.triggerAction('actionName', { limit });
    });

    // listen to messages sent from UI Bakery
    bakery.onMessage('eventName', params => {
      console.log(params);
    });
  });
</script>
```

## Listen to messages from UI Bakery in the host app

To listen to messages from UI Bakery, use the `bakery.onMessage('eventName')` method:

* In your host app, listen to a message from a UI Bakery app:

```javascript
bakery.onReady(() => {
  //...

  bakery.onMessage('eventName', params => {
    console.log(params);
  });
});
```

* In the UI Bakery app, send the message (for example, in an Action code) so that it can be received by the host app.

```javascript
UIBakeryEmbedded.emitMessage('eventName', {{data}})	;
```

## Send a message from the host app to UI Bakery

To send a message from the host app to UI Bakery, use `bakery.triggerAction('actionName', { ... });` method. This method triggers a specific action and passes the second argument as a `{{params}}` variable:

* In your host app, trigger an action with the custom params:

```javascript
bakery.onReady(() => {
  //...
  bakery.triggerAction('setUser', { user: 'email@example.com' });
});
```

* In the UI Bakery app, create the 'setUser' action and use `{{params}}` variable to receive the data:

```javascript
// ... setUser action
console.log({{params.user}});

return {{params.user}}
```
