Skip to content

Commit

Permalink
Custom a/b testing script with nonces
Browse files Browse the repository at this point in the history
  • Loading branch information
jhonatan-lopes committed Feb 19, 2024
1 parent 97f9344 commit e952370
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions network-api/networkapi/templates/wagtail_ab_testing/script.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
{% load static %}

{% if track %}
{# Is this a Wagtail Page? #}
{% if page %}
{# This value is used to check if a goal has been reached #}
{{ page.id|json_script:"abtesting-page-id" }}
{% endif %}

{# Is there a test running on the current page? #}
{% if test and version %}
{{ test.id|json_script:"abtesting-test-id" }}
{{ version|json_script:"abtesting-version" }}
{{ test.goal_event|json_script:"abtesting-goal-event" }}
{% if test.goal_page %}
{{ test.goal_page.id|json_script:"abtesting-goal-page-id" }}
{% else %}
{{ None|json_script:"abtesting-goal-page-id" }}
{% endif %}
{% endif %}

{# URLs #}
{% url 'wagtail_ab_testing:register_participant' as register_participant_url %}
{{ register_participant_url|json_script:"abtesting-register-participant-url" }}
{% url 'wagtail_ab_testing:goal_reached' as goal_reached_url %}
{{ goal_reached_url|json_script:"abtesting-goal-reached-url" }}

<script nonce="{{ request.csp_nonce }}">
// Read values from the DOM
const pageId = JSON.parse(document.getElementById('abtesting-page-id').textContent);
const testId = JSON.parse(document.getElementById('abtesting-test-id').textContent);
const version = JSON.parse(document.getElementById('abtesting-version').textContent);
const goalEvent = JSON.parse(document.getElementById('abtesting-goal-event').textContent);
const goalPageId = JSON.parse(document.getElementById('abtesting-goal-page-id').textContent);
const registerParticipantUrl = JSON.parse(document.getElementById('abtesting-register-participant-url').textContent);
const goalReachedUrl = JSON.parse(document.getElementById('abtesting-goal-reached-url').textContent);

window.wagtailAbTesting = {
pageId: pageId,
testId: testId,
version: version,
goalEvent: goalEvent,
goalPageId: goalPageId,

urls :{
registerParticipant: registerParticipantUrl,
goalReached: goalReachedUrl
}
};
</script>

<script nonce="{{ request.csp_nonce }}" src="{% static 'wagtail_ab_testing/js/tracker.js' %}" defer async></script>
{% endif %}

0 comments on commit e952370

Please sign in to comment.