Access metafields data in ScriptTag?

maxmueller
New Member
2 0 0
With my App I want to show an element on the storefront, that shows content depending on settings that the shop owner is setting in the admin panel. But I'm stuck with accessing store data from the ScriptTag.

Here is the scripttag code:

 

jQuery(document).ready(function() {
  var metafield_value = get_metafield_value(); // --->>>> HOW WOULD I GET METAFIELD VALUES HERE?
  $('body').prepend('<h2>'+metafield_value+'</h2>');
});​



 

On the server, I set my script tag like this:

 

...
app.prepare().then(() => {
const server = new Koa();
...

server.use(
createShopifyAuth({
...
async afterAuth(ctx) {
const { shop, accessToken } = ctx.session;
...
const scriptUrl = `https://${shop}/admin/api/2019-10/script_tags.json`;
const options = {
credentials: 'include',
headers: {
'X-Shopify-Access-Token': accessToken,
'Content-Type': 'application/json',
},
};
const requestBody = {
"script_tag": {
"event": "onload",
"src": `https://myserver/script.js`,
}
};

const optionsWithPost = { ...options, method: 'POST', body: JSON.stringify(requestBody) };

fetch(`${scriptUrl}`, optionsWithPost);
};
}
})
);

 

 

And the server can return metafield values like this:

 

...
router.post('/get_metafield',function(req,res){
var metafield_value = get_metafield();
res.end(metafield_value);
});

 

 
There seem to be similar questions on the forum but none of them provides an answer with code that shows how to do that.

 

How could I get the metafield value in the scripttag?
0 Likes
AKS7891
New Member
1 0 1

You will need to use JSONP in your script tag to make a call to your app server and get the configuration.

//register loadSettings
window["loadSettings"] = function (settings) {
  const whatYouNeed = JSON.parse(settings);
  // Use the above, as you like.
};

var script = document.createElement("script");
script.src=`https://<your-server-url>/<route-path>`;
document.head.appendChild(script);

 

Make sure that that the above route does not need authentication and  then your server should return configuration as JSON, something like below:

res.setHeader("Content-Type", "application/json");
const resJson = JSON.stringify(`{"settings": "{Your data}"}`);
return res.json(`window['loadSettings'](${resJson})`);