【问题标题】:Javascript: Passing variable into ShopifyApp initializeJavascript:将变量传递到 ShopifyApp 初始化
【发布时间】:2014-03-16 11:50:38
【问题描述】:

我正在构建一个使用Shopify Embedded App SDK 的应用程序。我正在尝试从请求 url 中提取一个参数,并将其传递给嵌入式应用程序的 javascript 初始化函数。但是捕获的变量没有按预期插入。

我可以成功地从请求中捕获参数,但是变量永远不会在初始化函数中输出。

到目前为止,这是我的代码:

<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(我不能在这个特定页面中使用)。

关于如何将捕获的参数传递给初始化函数的任何想法?

【问题讨论】:

    标签: javascript jquery shopify


    【解决方案1】:

    不确定但可能是异步概念的问题,请在制作后使用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
          });
    
    }
    

    【讨论】:

    • 太棒了,这把戏做得很漂亮.. 非常感谢! :)
    • 你为什么要这样做?如果您的 App 代码在商店的客户端运行,您可以从服务器端响应中了解商店。因此,您无需从 URL 中解析它,您只需从会话中获取它。好奇地想知道你为什么要这样做……
    • 是的,我承认这似乎有点倒退......我需要知道正在访问我的 shopifyshop 的 shopifyshop 的 shopify 商店 ;) 你最终会看到.. 一切顺利.
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-19
    • 2021-05-22
    • 2023-03-06
    • 2020-02-02
    • 2019-07-06
    • 2022-01-12
    • 1970-01-01
    相关资源
    最近更新 更多