Track WebViews (Beta)

A newer version of this documentation is available. Switch to the latest version docs.

Once the WebView Tracking Tag is implemented in the web pages, you need to wrap any tracked WebView in the ContentsquareWebViewTrackerBuilder Widget.

You can omit using our plugin and implement tracking your webviews manually (for example if you use a custom webView package).
In that case you need to use the ContentsquareWebViewTrackerBuilder widget constructor.

The builder provides a tracker with three methods, that need to be called in the following order:

  1. tracker.registerWebViewController: registers the ContentsquareWebViewController with the tracker.
  2. tracker.javascriptChannels: a set of (JavaScript) channels that you must register for the communication between Contentsquare and the WebView
  3. tracker.startPageTracking: this method must be called every time a new page has finished loading.

See the following section for implementation examples featuring the most popular webview packages.

If you are using the flutter_inappwebview, use the following code can be used to track a webview:

ContentsquareWebViewTrackerBuilder(
builder: (context, tracker) {
return InAppWebView(
initialUrlRequest: URLRequest(
url: Uri.parse('https://your_tracked_webview.com'),
),
onWebViewCreated: (controller) {
tracker.registerWebViewController(
ContentsquareWebViewController(
evaluateJavascript: (source) async {
return '${await controller.evaluateJavascript(source: source)}';
},
currentUrl: () async => '${await controller.getUrl()}',
javascriptChannelCall: (channelName, data) {
return 'window.flutter_inappwebview.callHandler("$channelName", $data)';
},
),
);
for (final javascriptChannel in tracker.javascriptChannels) {
controller.addJavaScriptHandler(
handlerName: javascriptChannel.name,
callback: (args) {
return javascriptChannel.onMessageReceived(args.first);
},
);
}
},
onLoadStop: (controller, uri) async {
//
// This MUST be called AFTER the controller is registered and the JavaScript
// channels are available
await tracker.startPageTracking();
},
);
},
)

To validate that the WebView tracking is working correctly, check the logs in your Flutter console.
Opening a screen with tracked WebView will result in the following log:

Terminal window
┌───────────────────────────────────────────────────────────────────────────────
ℹ️ INFO ℹ️ (CSLIB) [Tracked WebView]
├───────────────────────────────────────────────────────────────────────────────
WebView tracking enabled on WebView with initialUrl:
https://your.tracked.website
└───────────────────────────────────────────────────────────────────────────────