我正在构建一个使用Shopify Embedded App SDK的应用。我试图从请求网址中提取一个参数,并将其传递给嵌入式应用的javascript初始化函数。但是,捕获的变量不会按预期插入。
我可以成功捕获请求中的参数,但是变量永远不会在initialize函数中输出。
到目前为止,这是我的代码:
<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>
我可以使用普通的javascript或jquery,但请注意我对两者都是菜鸟,主要是熟悉rails(我不能在这个特定的页面中使用)。
关于如何将捕获的参数传递给初始化函数的任何想法?
答案 0 :(得分:2)
不确定但是可能是异步概念的问题,在创建它之后使用urlParams
。
(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
});
}