Skip to content

Adding the Braze JavaScript interface to WebViews

Learn how to add the Braze JavaScript interface to your iOS app, so you can leverage Braze in custom WebViews. After you add the interface, you’ll be able to use the API for HTML in-app messages in your custom WebViews.

About the interface

The Braze ScriptMessageHandler is responsible for:

  1. Injecting the Braze Javascript bridge into your WebView, as outlined in HTML in-app messages.
  2. Passing the bridge methods received from your WebView to the Braze Swift SDK.

Adding the interface to a WebView

First, add the ScriptMessageHandler from WebViewBridge to your app.

1
let scriptMessageHandler = Braze.WebViewBridge.ScriptMessageHandler(braze: braze)

Add the initialized scriptMessageHandler to a WkWebView’s userContentController.

1
2
3
4
configuration.userContentController.add(
  scriptMessageHandler,
  name: Braze.WebViewBridge.ScriptMessageHandler.name
)

Then create the WebView using your configuration.

1
let webView = WKWebView(frame: .zero, configuration: configuration)

When you’re finished, your code should be similar to the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// Create the script message handler using your initialized Braze instance.
let scriptMessageHandler = Braze.WebViewBridge.ScriptMessageHandler(braze: braze)

// Create a web view configuration and setup the script message handler.
let configuration = WKWebViewConfiguration()
configuration.userContentController.addUserScript(
  Braze.WebViewBridge.ScriptMessageHandler.script
)
configuration.userContentController.add(
  scriptMessageHandler,
  name: Braze.WebViewBridge.ScriptMessageHandler.name
)

// Create the webview using the configuration
let webView = WKWebView(frame: .zero, configuration: configuration)

Example: Logging a custom event

In the following example, BrazeBridge is used to log a custom event from existing web content to the Braze Swift SDK.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Logging data via BrazeBridge Example</title>
    <script>
      function logData(data) {
        window.brazeBridge.logCustomEvent(data);
      }
    </script>
  </head>

  <body>
    <input
      type="button"
      value="Click to log a custom Event 'completed_level'"
      onclick="logData('completed_level')"
    />
  </body>
</html>
HOW HELPFUL WAS THIS PAGE?
New Stuff!