繁体   English   中英

检测URL更改而无哈希或后退/前进popstate

[英]Detect URL change without a hash or back/forward popstate

TLDR;

我有一个URL,它的结束位会随着选项select的改变而改变:

www.mywebsite.com?variant=13390743207991

要么

?variant=13400659984439

我想知道是否有办法检测到这种变化。 我已经可以使用setInterval做到这一点,并且只需0.5秒就可以捕获URL来检测更改,但是有没有比这更有效的方法了?

全文

我对这方面的JavaScript很陌生,所以如果我错了,请纠正我。

我正在为Shopify网站开发一些工作。 据我所知,Shopify为特定产品提供了一个产品变体选择器,在其中动态地填充了选定的产品和产品价格。

在向选择表单添加新类后,我意识到它们会在创建时自动删除,这使我很难检查是否选择了新选项。 一个例子看起来像这样:

 <select name="id"  id="productSelect-{{ product.id }}" class="product-single__variants">
  {% for variant in product.variants %}
    {% if variant.available %}
      <option  {% if variant == current_variant %} selected="selected" {% endif %} value="{{ variant.id }}" data-sku="{{ variant.sku }}">{{ variant.title }}</option>
    {% else %}
      <option>
        {{ variant.title }} - {{ 'products.product.sold_out' | t }}
      </option>
    {% endif %}
  {% endfor %}
</select>

我创建了一个实用程序,用于检测用户visitor上的地理位置,从而相应地调整产品价格(USD,CAD等)。

考虑到我无法检测到Shopify泡沫之外的某个变体是否发生变化,一旦变体发生变化,我就无法调整显示的价格。 它最初是通过液体代码中的赋值变量进行调整的。

我确实注意到,页面的URL随变体更改而改变:

?variant=13390743207991

要么

?variant=13400659984439

多余的部分在URL的末尾被标记。

我想知道是否有任何方法可以检测到该URL更改,从而可以在选择变体时调整价格。

如果您使用默认的shopify脚本,请使用它们提供的回调。 更多信息在这里

  var selectCallback = function(variant, selector) {
    // do stuff
  }

  new Shopify.OptionSelectors('product-variant-selector', {
    product: {{ product | json }},
    onVariantSelected: selectCallback, 
    enableHistoryState: true 
  });

您是否尝试过位置栏

var LocationBar = require("location-bar");
var locationBar = new LocationBar();

// listen to all changes to the location bar
locationBar.onChange(function (path) {
  console.log("the current url is", path);
});

// listen to a specific change to location bar
// e.g. Backbone builds on top of this method to implement
// it's simple parametrized Backbone.Router
locationBar.route(/some\-regex/, function () {
  // only called when the current url matches the regex
});

locationBar.start({
  pushState: true
});

// update the address bar and add a new entry in browsers history
locationBar.update("/some/url?param=123");

// update the address bar but don't add the entry in history
locationBar.update("/some/url", {replace: true});

// update the address bar and call the `change` callback
locationBar.update("/some/url", {trigger: true});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM