Reputation: 470
I'm building a we app which uses the Shopify Embedded App SDK. I'm trying to extract a param from the request url, and passing this into a javascript initialize function for the embedded app. However the captured variable doesn't insert as expected.
I can successfully capture the params from the request, however the variable never outputs within the initialize function.
Here's my code so far:
<script src="//cdn.shopify.com/s/assets/external/app.js?123445566"></script>
<script type="text/javascript">
//Capture the params from the URL = Works fine
var urlParams;
(window.onpopstate = function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
urlParams = {};
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
//This is the part I am having troubles with, the urlParams["shop"] just outputs "urlParams["shop"]" instead of the value
ShopifyApp.init({
apiKey: "thiscontainsthecorrectapikeyvalue", // Expects: 32 character API key string like ff9b1d04414785029e066f8fd0465d00
shopOrigin: 'https://' + urlParams["shop"], // Expects: https://exampleshop.myshopify.com
debug: true
});
//This alert works as expected, and shows the correct value: "exampleshop.myshopify.com"
alert(urlParams["shop"]);
</script>
I can use plain javascript or jquery, but please note I am noob to both, mainly familiar with rails (which I cannot use in this particular page).
Any ideas on how to pass the captured param into the initialize function?
Upvotes: 1
Views: 767
Reputation: 6349
Not sure but can be the problem of asynchronous concept, use the urlParams
after made it.
(window.onpopstate = function () {
......
......
urlParams = {};
while (match = search.exec(query)){
urlParams[decode(match[1])] = decode(match[2]);
}
callInit(urlParams); //use when it is made
})();
function callInit(urlParams){
ShopifyApp.init({
apiKey: "thiscontainsthecorrectapikeyvalue", //API Key
shopOrigin: 'https://' + urlParams["shop"],
debug: true
});
}
Upvotes: 2