Detecting if in Theme Preview with JavaScript

Hi there,

As an app developer, I expose some theme blocks and Javascript functionality into online store themes.

I want to offer a “test mode” to merchants when they’re specifically previewing their online store:

This way they can test the functionality of the app, without performing the real actions. And real customers won’t be able to see this test option.

The closest option I’ve found in the documentation is regarding this is detecting the Theme Editor.

It mentions a variable called Shopify.inspectMode which I thought would fit the bill, but none of the variables seem to populate.

Is there another Javascript variable dedicated to detecting if the theme is in Online Preview mode?

Separately, it looks like the window.Shopify object is missing in the theme editor. Maybe this is a bug?

Not aware of any specific variable, but you could consider using something like:

let inPreviewMode = !!document.getElementById('OnlineStorePreviewBarNextData');

However, it’s a bit fragile, since it would break if Shopify changes the implementation of the preview bar in the future.

1 Like

Nice workaround, the presence of that element should prove they’re in the preview mode.

Yea I wish there was an official property in the Shopify object, but that should work in the meantime I think.

You could consider using Shopify.theme.role, which should tell you if user is on a theme other than live theme, which maybe useful. Also available in liquid.
Could also check document.cookie for _ab that determines if preview bar is shown.

I would actually consider creating your own preview logic, based on a URL param, would be cleanest and easiest.