How to use JavaScript to check if your script is running on a Shopify storefront's product page

If you're building a Shopify app, writing a theme, or even if you're a merchant running your own store, there might eventually come a time when you want to add somecustom JavaScript to enhance a Shopify store's product page. Maybe you need to add image or file uploading; maybe you want to track conversions and clicks; maybe you want to create some kind of product customizer.

Whatever you're doing, you don't always get to choose which page your script is loaded on. That's especially true if you're writing an app and using the Script Tag API -- Script Tags get loaded on every page on the storefront, not just the product page. And if that's the case, you'll need to write the script to check when it's on the product page so it knows when to go to work and when to take it easy.

This is exactly what I had to do with a recent client's project, where we needed to enhance the product page with some custom JavaScript. After a lot of experimentation with modifying liquid and HTML tags to insert some flag the script could look for, I realized that it's possible to use the Shopify storefront's AJAX API to do this. There's a specific endpoint that can be called to get product data, but you need to know the product's handle to use it.

The handle is just the product's URL "slug" or whatever you want to call it. Typically it's just the product's title but hyphenated and lowercased, so if the product's name is My Fabulous Product, then the handle might be my-fabulous-product. Emphasis on the world might though -- the merchant (and apps) can edit the handle, and even make it something completely different or nonsensical.

If you know the handle, you just make a request to /products/{handle}.json and you'll get the product's JSON object back. "That's all well and good," you might say, "but how does that help me check if I'm on a product page?" Easy! If the product page is being looked at, the product's handle is already in the address bar!

When viewing a product, the handle is already in the address bar

And of course, you can easily get the current URL in JavaScript with window.location.href, or just the path itself with window.location.pathname. Once you have the current path, all you have to do is strip off everything but the handle (the very last segment of the path), and use it to query the product API by tacking on .json. If the request returns 200 and a product object, you're on a product page! If it returns 404 (or some other non-200 status code), you're not on a product page.

/**
 * Checks if the script is currently running on a product page by attempting to get the product's API object.
 */
async function onProductPage() {
    const path = window.location.pathname;
    // The pathname most likely looks like /collections/something/products/product-handle
    const potentialHandle = path.substring(path.lastIndexOf("/") + 1);
    const result = await fetch(`/products/${potentialHandle}.json`, {
        method: "GET",
        headers: {
            "Accept": "application/json"
        }
    });

    return result.status === 200;
}

There you have it, a fully functional example for checking if your JavaScript snippet is running on a product page! This does have the caveat that it can take a second or two for your script to start up; first the script itself needs to be loaded/parsed by the browser, and then it needs to make the request.

There are a few ways you could speed this process up, depending on your use case:

  1. If you're building an app and using Script Tags, you could build it in such a way that you already know the handles for products when the script is loaded. In this scenario you'd ask your user to pick which products your script will interact with, and then you point the Script Tag URL at your server where you can inject the product handles alongside the script itself. This lets you skip the request to the product API, instead you'd just look for the handle in the URL.
  2. Some Shopify stores have a JS meta object loaded on the page by their theme. This meta object can contain product data. This cannot be relied on though, it depends on the theme and the theme developer to put it there; but if it is there, you can skip the product API call. The meta object
  3. You can look for a form that submits to /cart/add. Once again this isn't 100% reliable, it still depends on the theme the storefront is using. There's no standardized HTML or CSS guidelines for Shopify themes, so it's up to the theme developer's discretion.

Personally, I often use #2 and #3 in my scripts, and then fall back to making a call to the products API if I'm unable to find a meta object or a form that submits to /cart/add.


Learn how to build rock solid Shopify apps with C# and ASP.NET!

Did you enjoy this article? I wrote a premium course for C# and ASP.NET developers, and it's all about building rock-solid Shopify apps from day one.

Enter your email here and I'll send you a free sample from The Shopify Development Handbook. It'll help you get started with integrating your users' Shopify stores and charging them with the Shopify billing API.

We won't send you spam. Unsubscribe at any time.