gtag_js/lib.rs
1#![ deny(missing_docs)]
2
3//! This crate provides a rustic wrapper around Google's gtag.js tagging framework.
4//!
5//! To use this crate the `gtag()` javascript function must have already been defined as described
6//! in the relevant [documentation].
7//!
8//! [documentation]: https://developers.google.com/gtagjs/devguide/snippet
9
10use wasm_bindgen::prelude::*;
11use serde::ser::Serialize;
12
13/// A wrapper around Google's gtag.js framework.
14pub struct DataLayer {
15 id: String,
16}
17
18impl DataLayer {
19 /// Create a `DataLayer` object that can be used to push data with the given ID.
20 pub fn new(id: impl Into<String>) -> Self {
21 DataLayer {
22 id: id.into(),
23 }
24 }
25
26 /// Push data with no parameters.
27 pub fn push_simple(&self, cmd: &str) {
28 gtag_js_sys::gtag(cmd, &self.id);
29 }
30
31 /// Push data with the given parameters.
32 ///
33 /// This function can fail if there is an error serializing the data to a [`JsValue`].
34 ///
35 /// As a parameter value, this accepts any type that can be serialized to Json using Serde.
36 /// This can be done by deriving `Serialize` from `serde` or using the `json!` macro from
37 /// `serde_json`.
38 ///
39 /// ```
40 /// #[derive(Serialize)]
41 /// struct Pageview {
42 /// page_title: Option<String>,
43 /// page_location: Option<String>,
44 /// page_path: Option<String>,
45 /// }
46 /// ```
47 /// ```
48 /// json!({
49 /// "page_title": "index.html",
50 /// "page_path": "/",
51 /// })
52 /// ```
53 ///
54 /// [`JsValue`]: https://docs.rs/wasm-bindgen/0.2.58/wasm_bindgen/struct.JsValue.html
55 pub fn push(&self, cmd: &str, params: &impl Serialize) -> serde_json::error::Result<()> {
56 gtag_js_sys::gtag_with_parameters(cmd, &self.id, &JsValue::from_serde(params)?);
57 Ok(())
58 }
59}