Save the referring document URL as a JSON variable

Mission: The objective is to send the JSON data to Google Tag Manager.

Issue at Hand: Unfortunately, Shopify Documentation does not provide a liquid variable for 'referrer'.

Potential Fix: One possible solution is to create a variable using JavaScript.

My Approach:

  1. I have developed a script that appends the URL of the website from where visitors are coming.

  2. The appended website URL is then captured and converted into a variable.

  3. The variable {{ ref }} is inserted into the JSON.

Upon inspection of the element, it was noticed that the 'referrer' field in the JSON was empty.

Requesting assistance on this matter.

<script type="text/javascript">
$(document).ready(function () {
    var content = document.referrer;
    $(".referrer").append(content);
});  
</script>

{% capture ref %}
<div class="referrer">Referrer: </div>
{% endcapture %}


<script type="text/javascript">  
dataLayer.push({
  ‘userEmail’ : ‘{{ customer.email }}’,
  ‘productCategory’ : ‘{{ collection.title }}’,
  ‘productName’ : ‘{{ product.title }}’,
  ‘price’ : ‘{{ sca_price | money }}’,
  ‘originalPrice’ : ‘{{ sca_price | money }}’,
  ‘cartItems’ : ‘{{ cart.item_count }}’,
  ‘currency’ : ‘{{ shop.currency }}’,
  ‘referrer’ : ‘{{ ref }}’, // issue persists
  ‘productRating’ : ‘’,
  ‘reviewCount’ : null,
  ‘event’ : null
});  
</script>

Answer №1

Discovering the referrer on Shopify doesn't require a specific variable. There's no need to store it in a page variable either. Simply make this adjustment:

‘referrer’ : ‘{{ ref }}’, // not functioning

change it to

‘referrer’ : document.referrer,

Update:

Implement the following code:

<script type="text/javascript">  
    push_data = {
      'userEmail' : '{{ customer.email }}',
      'productCategory' : '{{ collection.title }}',
      'productName' : '{{ product.title }}',
      'price' : '{{ sca_price | money }}',
      'originalPrice' : '{{ sca_price | money }}',
      'cartItems' : '{{ cart.item_count }}',
      'currency' : '{{ shop.currency }}',
      'productRating' : '',
      'reviewCount' : null,
      'event' : null
    }
    push_data['referrer'] = document.referrer;
    console.log(push_data); //delete this section. It's just to verify if referrer is filled
    dataLayer.push(push_data);  
</script>

Answer №2

To implement this feature, you can utilize JavaScript:

"referrer": document.referrer

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jq encountered an issue: Attempting to index an array with a string is not

I am currently working on a bash script for a checkpoint management server API, but I have encountered some issues. My goal is to extract a value from a JSON dictionary using variables. Here is the command I have been using: echo $rulebase | jq --arg n "$ ...

Troubleshooting a ThreeJS Issue: the Mystery of the Malfunction

I have a ribbon showcasing various thumbnails. These thumbnails are painted on a canvas and then added to a Texture. var texture = new THREE.Texture(textureCanvas); The mesh is generated as shown below loader.load('mesh_blender.js', functi ...

Tips for utilizing XMLHttpRequest to instruct a website to take action

Although I have no prior experience with Ajax, I am in need of some guidance to create a simple Chrome extension. Despite searching online, I have not been able to find much information on this topic, which I believe should be straightforward. Request URL ...

What is the best way to prevent a page refresh in PHP when data is incomplete?

I have a web page containing two forms, each with an input field and a button named submit1 and submit2. My goal is to use JavaScript to submit the data when content 1 is selected. When content 2 is linked, form2 should be displayed. Upon clicking submit ...

Guide on setting the dropdown's selected index through JavaScript

Is there a way to use javascript to set the selected value of a dropdown? Here is the HTML code I am working with: <select id="strPlan" name="strPlan" class="formInput"> <option value="0">Select a Plan</option> </select> I am ...

Transferring a Sharepoint 2010 List Item between folders

Currently, I am facing an issue while attempting to transfer a list item from one folder to another. Despite utilizing a code that I discovered (the link to the source of the code can be found below), I keep encountering an error message stating "Value doe ...

HTML embedded content is not appearing on the React webpage

I'm attempting to incorporate GoFundMe donation buttons into a React page, but unfortunately, they aren't displaying on the screen. const Donation = () => { return ( <div> <div className="gfm-embed" d ...

Sending JSON information between activities using AsyncTask

My goal is to read a JSON file and pass its data to another Activity by creating a ListView. However, I am unsure of where exactly I need to set the Intent. This code snippet shows the SplashScreen where I retrieve the JSON: public class SplashScreen exte ...

Using the `find()` method in a loop of Mongoose iterate

Searching for documents based on conditions stored in an array can be quite useful. Take this example: subscriptions=[ {teacher: 'john', student:'david' ,course:'math'}, {teacher: 'john', student:'david' , ...

The error with Bootstrap4 alpha6 modal is in the process of transitioning

Currently, I am facing an issue with the bootstrap4 alpha 6 modal. The error message I am receiving is: Error: Modal is transitioning This occurs when attempting to re-trigger the same modal with dynamic data using a JavaScript function like this: funct ...

How can I improve my skills in creating efficient Angular routers?

In my Ionic project, I am dealing with an AngularJS routes file that contains a large number of routes, approximately a hundred. The structure is similar to the one provided below. (function() { 'use strict'; angular.module('applicatio ...

Error message 'Module not found' occurred when trying to incorporate Axios library into project

Hey there! I am encountering a similar issue as described in this post ('Module not found' babel error after installing axios). Despite trying all the recommended solutions, the error continues to persist: Failed to compile ./src/apis/youtube. ...

Using jQuery to dynamically load custom post type data in WordPress upon clicking

Let me explain my current project setup. I have developed a custom post type called "People" and have created several individual posts within it. At the moment, I have successfully implemented a modal using JavaScript with static content. Instead of disp ...

Having trouble turning octet-stream response data into a downloadable Zip file

I've been attempting to download a Zip file that contains JSON files through an AJAX GET request. Here is the format of the response headers: Connection: keep-alive content-disposition: attachment;filename=exportedFiles_ 1.6.0_20200731160652.zip Cont ...

The API response from wp-json returns a 401 error when attempting to edit a post using React and

Working on creating an admin page within WordPress using React for managing post content. Successfully implemented a delete method in React that interacts with the API, but facing challenges with getting the update method to function correctly. // plugin_ ...

Struggling with the performance of my JavaScript canvas map script

Below is the script I've written for a prototype that utilizes 128x128 tiles to create a map on a canvas that can be dragged around by the user. The script is functioning, but I'm facing some challenges: 1. Poor performance that needs to be addr ...

Waiting for the listener script to finish its task in an Ajax call and then informing the user

I have developed a unique program that allows users to submit test cases from a specific webpage (main.php). The webpage triggers an ajax request to insert user data into MySQL using the file insert.php, with the value done=0. Subsequently, there is a list ...

Is it possible to retrieve the index of a particular element within an array during an update operation in MongoDB?

After executing the following update statement const result = await Post.updateOne({_id: postId},{ $pull: {reacts: {publisher: req.query.publisher}}, $inc: {postPoints: - reactsEnum[ReactType]} }); I am interested in obtaining the ...

Error in Angular4 Typescript: The 'data' property is not found on the 'any[]' type

During my development of an Angular 4 app using TypeScript, I encountered an error that states: Property 'data' does not exist on type 'any[]' This error occurs when trying to access the 'data' property in the following co ...

What is causing the data added to an array to vanish after the forEach loop within the useEffect hooks?

Below is the code snippet: const Tabs = ({data, scrollX}) => { const [measures, setMeasures] = useState([]); const containerRef = useRef({}); let measureMentArray = []; useEffect(() => { data && data.forEach(item => { ...