Skip to content

Commit

Permalink
Add url option
Browse files Browse the repository at this point in the history
  • Loading branch information
ScarletKuro committed Sep 26, 2024
1 parent d17ee7f commit d9da4d9
Show file tree
Hide file tree
Showing 7 changed files with 64 additions and 31 deletions.
11 changes: 8 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,13 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.

## [Unreleased]

## [4.0.0] - 2024-12-01
### Added
- `Url` property to `GoogleTagManagerOptions`.
- `url` parameter in `IGoogleTagManagerInterop.InitializeAsync`.

## [3.0.0] - 2024-08-26
### Remove
### Removed
- `IGoogleTagManagerInterop` from `IGoogleTagManager`.

### Added
Expand Down Expand Up @@ -44,8 +49,8 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
### Changed
- Remove Havit.Core.

[Unreleased]: https://github.com/ScarletKuro/Blazor.GoogleTagManager/compare/HEAD..3.0.0

[Unreleased]: https://github.com/ScarletKuro/Blazor.GoogleTagManager/compare/HEAD..4.0.0
[4.0.0]: https://github.com/ScarletKuro/Blazor.GoogleTagManager/compare/3.0.0..4.0.0
[3.0.0]: https://github.com/ScarletKuro/Blazor.GoogleTagManager/compare/2.0.0..3.0.0
[2.0.0]: https://github.com/ScarletKuro/Blazor.GoogleTagManager/compare/1.1.1..2.0.0
[1.1.1]: https://github.com/ScarletKuro/Blazor.GoogleTagManager/compare/1.1.0..1.1.1
Expand Down
3 changes: 3 additions & 0 deletions src/Blazor.GoogleTagManager/Blazor.GoogleTagManager.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@
<Pack>True</Pack>
<PackagePath>\</PackagePath>
</None>
<None Include="..\..\CHANGELOG.md">
<Pack>False</Pack>
</None>
</ItemGroup>

<ItemGroup>
Expand Down
17 changes: 8 additions & 9 deletions src/Blazor.GoogleTagManager/GoogleTagManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,16 +40,10 @@ public GoogleTagManager(
}

/// <inheritdoc/>
public void EnableTracking()
{
IsTackingEnabled = true;
}
public void EnableTracking() => IsTackingEnabled = true;

/// <inheritdoc/>
public void DisableTracking()
{
IsTackingEnabled = false;
}
public void DisableTracking() => IsTackingEnabled = false;

/// <inheritdoc/>
public async Task InitializeAsync()
Expand All @@ -59,12 +53,17 @@ public async Task InitializeAsync()
return;
}

if (string.IsNullOrEmpty(_gtmOptions.Url))
{
throw new ArgumentException("URL cannot be empty.", nameof(_gtmOptions.Url));
}

if (string.IsNullOrEmpty(_gtmOptions.GtmId))
{
throw new ArgumentException("GTM Id cannot be empty.", nameof(_gtmOptions.GtmId));
}

await _googleTagManagerInterop.InitializeAsync(_gtmOptions.GtmId, _gtmOptions.Attributes, _gtmOptions.DebugToConsole);
await _googleTagManagerInterop.InitializeAsync(_gtmOptions.Url, _gtmOptions.GtmId, _gtmOptions.Attributes, _gtmOptions.DebugToConsole);

IsInitialized = true;
}
Expand Down
33 changes: 25 additions & 8 deletions src/Blazor.GoogleTagManager/GoogleTagManagerOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,36 +8,53 @@ namespace Blazor.GoogleTagManager;
public class GoogleTagManagerOptions
{
/// <summary>
/// GTM-ID.
/// Gets or sets the URL of the Google Tag Manager script.
/// For more information, see <see href="https://developers.google.com/tag-platform/tag-manager/server-side/custom-domain">Custom Domain for Google Tag Manager</see>.
/// <para/>
/// The default value is <c>https://www.googletagmanager.com</c>.
/// </summary>
/// <remarks>
/// Do not add a trailing slash '/' at the end of the URL.
/// </remarks>
public string Url { get; set; } = "https://www.googletagmanager.com";

/// <summary>
/// Gets or sets the GTM-ID.
/// The default value is an empty string.
/// </summary>
public string GtmId { get; set; } = string.Empty;

/// <summary>
/// Google Tag Manager script attributes.
/// Gets or sets the Google Tag Manager script attributes.
/// The default value is an empty dictionary.
/// </summary>
public Dictionary<string, string> Attributes { get; set; } = new();

/// <summary>
/// Name of the event pushed when page-view is tracked.
/// Gets or sets the name of the event pushed when a page-view is tracked.
/// The default value is <c>"virtualPageView"</c>.
/// </summary>
public string PageViewEventName { get; set; } = "virtualPageView";

/// <summary>
/// Name of the variabel to be used for URL when page-view is tracked.
/// Gets or sets the name of the variable to be used for the URL when a page-view is tracked.
/// The default value is <c>"pageUrl"</c>.
/// </summary>
public string PageViewUrlVariableName { get; set; } = "pageUrl";

/// <summary>
/// Allows to print logs in the browser console. Do not use in production.
/// Gets or sets a value indicating whether to print logs in the browser console.
/// Do not use in production.
/// The default value is <c>false</c>.
/// </summary>
public bool DebugToConsole { get; set; }

/// <summary>
/// Specifies whether to import the JavaScript <c>'_content/Blazor.GoogleTagManager/GoogleTagManager.js'</c> file automatically.
/// Gets or sets a value indicating whether to import the JavaScript <c>'_content/Blazor.GoogleTagManager/GoogleTagManager.js'</c> file automatically.
/// <para>
/// If you disable this option, you must manually import your own JavaScript via the <c>script</c> tag.
/// </para>
/// Default is <c>true</c>.
/// The default value is <c>true</c>.
/// </summary>
public bool ImportJsAutomatically { get; set; } = true;
}
}
18 changes: 13 additions & 5 deletions src/Blazor.GoogleTagManager/Interop/GoogleTagManagerInterop.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,34 +6,42 @@

namespace Blazor.GoogleTagManager.Interop;

/// <summary>
/// Provides interop methods for Google Tag Manager.
/// </summary>
internal class GoogleTagManagerInterop : IGoogleTagManagerInterop, IAsyncDisposable
{
private readonly IJSRuntime _jsRuntime;
private Task<IJSObjectReference>? _module;
private readonly IOptions<GoogleTagManagerOptions> _options;

private Task<IJSObjectReference> Module => _module ??= _jsRuntime.InvokeAsync<IJSObjectReference>(
"import", ["./_content/Blazor.GoogleTagManager/GoogleTagManager.js"])
"import", "./_content/Blazor.GoogleTagManager/GoogleTagManager.js")
.AsTask();

/// <summary>
/// Initializes a new instance of the <see cref="GoogleTagManagerInterop"/> class.
/// </summary>
/// <param name="gtmOptions">The Google Tag Manager options.</param>
/// <param name="jsRuntime">The JavaScript runtime.</param>
public GoogleTagManagerInterop(IOptions<GoogleTagManagerOptions> gtmOptions, IJSRuntime jsRuntime)
{
_options = gtmOptions;
_jsRuntime = jsRuntime;
}

/// <inheritdoc/>
public async Task InitializeAsync(string gtmId, Dictionary<string, string> attributes, bool debugToConsole)
public async Task InitializeAsync(string url, string gtmId, Dictionary<string, string> attributes, bool debugToConsole)
{
if (_options.Value.ImportJsAutomatically)
{
var module = await Module;

await module.InvokeVoidAsync("initialize", gtmId, attributes, debugToConsole);
await module.InvokeVoidAsync("initialize", url, gtmId, attributes, debugToConsole);
}
else
{
await _jsRuntime.InvokeVoidAsync("initialize", gtmId, attributes, debugToConsole);
await _jsRuntime.InvokeVoidAsync("initialize", url, gtmId, attributes, debugToConsole);
}
}

Expand Down Expand Up @@ -92,4 +100,4 @@ public async ValueTask DisposeAsync()
await module.DisposeAsync();
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,12 @@ public interface IGoogleTagManagerInterop
/// <summary>
/// Initializes the Google Tag Manager with the specified GTM ID, attributes, and debug option.
/// </summary>
/// <param name="url">URL of the Google Tag Manager script.</param>
/// <param name="gtmId">The Google Tag Manager ID.</param>
/// <param name="attributes">A dictionary of attributes to initialize with.</param>
/// <param name="debugToConsole">Indicates whether to output debug information to the console.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
Task InitializeAsync(string gtmId, Dictionary<string, string> attributes, bool debugToConsole);
Task InitializeAsync(string url, string gtmId, Dictionary<string, string> attributes, bool debugToConsole);

/// <summary>
/// Pushes generic data to the GTM data layer.
Expand Down
10 changes: 5 additions & 5 deletions src/Blazor.GoogleTagManager/wwwroot/GoogleTagManager.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
export function initialize(GTMID, attributes, debugToConsole = false) {
(function (w, d, s, l, i, m, k) {
export function initialize(url, GTMID, attributes, debugToConsole = false) {
(function (w, d, s, l, u, i, m, k) {
w[l] = w[l] || [];
w[l].push({
"gtm.start": new Date().getTime(),
Expand All @@ -9,17 +9,17 @@
j = d.createElement(s),
dl = l !== "dataLayer" ? "&l=" + l : "";
j.async = true;
j.src = "https://www.googletagmanager.com/gtm.js?id=" + i + dl;
j.src = u + "/gtm.js?id=" + i + dl;
for (const [key, value] of Object.entries(m)) {
j.setAttribute(key, value);
}
f.appendChild(j, f);
window.dataLayer.push({ event: "pageview" });
window.isGTM = true;
if (k) {
console.log("[GTM]: Configured with GtmId = " + i);
console.log("[GTM]: Configured with URL = " + u + ", and " + "GtmId = " + i);
}
})(window, document, "script", "dataLayer", GTMID, attributes, debugToConsole);
})(window, document, "script", "dataLayer", url, GTMID, attributes, debugToConsole);
}

export function push(data, debugToConsole = false) {
Expand Down

0 comments on commit d9da4d9

Please sign in to comment.