javascript - Detect URL change in querystring
问题描述
I am adding some script on a Shopify product page where I need to detect the URL change which happens on selection of a product option (handled by Shopify) for further use.
The URL change occurs when variants are selected with the query parameter (question mark) like this:
Variant 1 - my.shopify.domain/products/product1?variant=1234
Variant 2 - my.shopify.domain/products/product1?variant=5678
I have tried adding the 'hashchange' event but then realized it only works for '#' which is not the case here.
What should I do?
解决方案
请将此脚本粘贴到您的 product.liquid 文件中
<script>
var firstTimeUrl = document.URL;
document.addEventListener('change', function() {
var currentPageUrl = document.URL;
var url = new URL(currentPageUrl);
var isVariantUrl = url.searchParams.get("variant");
currentPageUrl = isVariantUrl ? currentPageUrl :isVariantUrl;
if(currentPageUrl && firstTimeUrl != currentPageUrl) {
firstTimeUrl = currentPageUrl;
console.log('variant_id: '+isVariantUrl+'')
}
});
</script>
推荐阅读
- tensorflow - 在 Tensorflow 2.0 中归档 tensorflow 张量的最佳方式?
- python - 在 Django 视图中散列
- mysql - 在 SQL 数据库中存储一个范围/多个范围(上限可能未知)
- oracle - 从 Oracle CLOB 创建新行并写入 HDFS
- reactjs - 为什么我在我的 axios GET 请求中得到 [object Object]?
- angular - nginx转发器参数到角度
- sql - 接受 id 并返回表的函数 - 如何为多个 id 调用它?
- paypal - Paypal 的四舍五入税额
- javascript - 将数组追加到本地存储对象
- c# - 错误 CS0118 'TestBuilder' 是命名空间,但用作类型