Access shop.permanent.domain in javscript inserted with a script_tag

Araxie
New Member
3 0 1

Hopefully this is an easy question for someone.

I can successfully insert Javascript using a  script tag, but how do I access the liquid variable shop.permanent.domain in my javascript?

Right now my .js looks like:

var shop={{shop.permanent_domain}};
var newPage="http://www.myserver.com?shop="; + shop;

function openNewPage(){
window.open(newPage)
}

0 Likes
Chris_Saunders
Shopify Staff
Shopify Staff
582 0 49

Script tags don't go through the liquid pipeline because it's just your server serving up the assets. If you need the permanent domain you could turn your JS file into a rendered template and feed in a locally cached shop object with all the data you need

# controller.rb
# /scripts/:shop_id
respond_to :js
def show
  @shop = Shop.find(params[:shop_id])
end

# scripts/show.js.erb
var shop = "<%= @shop.permanent_domain %>"
var newPage = "http://myserver.com?shop="; + shop

function openNewPage() { window.open(newPage); }

 

0 Likes
tmstn
New Member
1 0 0

I'm sorry for posting on such an old thread but I've been looking for a way to do this and thought I would leave this here in case anyone is searching for a solution in the future. There are a few ways I've discovered.

The first is to use unique js files for each store, which have been pre-generated by the app to include the shop domain as a variable.

The second is a dynamic version of the first where the script tag src points to a dynamic endpoint and contains a unique identifier which is linked to the shop domain in some way. The dynamic endpoint will generate and return the javascript containing the shop domain as a variable

The third and probably the easiest way is to attach the store domain as a query parameter to the script tag src property, then read this back in the javascript code itself by parsing the script tag src attribute. Below is a basic code example of how to get the shop domain from the script tag src property.

<!DOCTYPE html>
<html lang="">
<head>
  <meta charset="utf-8">
  <title></title>
  <script src="https://mydomain.com/scripts.js?shop=mydomain.myshopify.com"></script>
</head>
<body>
  <script>
    let scripts = document.querySelectorAll('script[src^="https://mydomain.com/scripts.js"]');
    if (scripts.length > 0) {
      const url = new URL(scripts[0].attributes['src'].value);
      console.log(url.searchParams.get('shop'));
    }
  </script>
</body>
</html>

       

0 Likes