Reputation: 29536
when my app is installed I create a script tag (through the shopify API). I am only interested in running this script on product view pages. what is a reliable way to check whether the script is run by a product view page? Should I ask the merchant to put something in to their liquid file manually?
Upvotes: 5
Views: 2636
Reputation: 808
This should work, in your JavaScript:
// If we are on a product page
if (window.location.pathname.indexOf('/products/') !== -1) {
// What's the product handle?
var productHandle = pathname.match(/\/products\/([a-z0-9\-]+)/)[1];
}
Upvotes: 5
Reputation: 11427
Write some generic Javascript to query the current URL in the browser. You can easily tell if you're on a page, product or collection. Try a simple RegExp to do this. It would be pretty hard for a shop to mess up the URL structure since Shopify is hosted.
Upvotes: -1
Reputation: 1039
The product page in Shopify always has a form on it that adds the product to the cart, so you can do something like this (assuming jQuery is available):
jQuery("form[action='/cart/add']").each(function() {
console.log("I'm in ur product page");
});
Upvotes: 0
Reputation: 12635
You can pass an extra function parameter specifying where the function was called from. I have used this kind of programming in a few projects with great success. For example:
function foo(data, moarData, caller) {
if(caller != 'productPage') { return false; }
...
}
And you can specify the caller variable from the function call on the product view page:
var page = 'productPage';
foo('sharks', 'games', this.page);
Upvotes: -1