javascript - 获取功能无限加载(Shopify)
问题描述
我已经尝试过了,但我无法添加 cookie 或区域设置存储条件,因此它不会无限重新加载。
fetch('https://get.geojs.io/v1/ip/country')
.then(response => response.text())
.then(country_code => {
var domain_and_tld = window.location.host.split('.').splice(-2).join('.');
country_code = country_code.trim().toLowerCase();
switch (country_code) {
case 'us':
window.location.host = domain_and_tld;
break;
case 'gb':
window.location.host = `${domain_and_tld}?currency=GBP`;
break;
case 'fr':
window.location.host = `${domain_and_tld}?currency=EUR`;
break;
};
})
.catch(err => console.error(err));
谢谢你的帮助 :)
解决方案
您似乎想根据用户国家/地区更改查询参数。我们不需要改变window.location.host
。您可以使用 更改查询参数window.location.search
。
但是,您只想window.location.search
在它与您想要的值不匹配时进行更改(以避免无限重新加载)。下面的解决方案假定货币是 URL 中唯一的查询参数。
fetch('https://get.geojs.io/v1/ip/country')
.then(response => response.text())
.then(country_code => {
const country_code = country_code.trim().toLowerCase();
let desiredSearchParams = '';
switch (country_code) {
case 'gb':
desiredSearchParams = `?currency=GBP`;
break;
case 'fr':
desiredSearchParams = `?currency=EUR`;
break;
case 'us':
default:
break;
};
if(desiredSearchParams !== window.location.search) {
//change search param only if desired search param different from current search param
window.location.search = desiredSearchParams;
}
})
.catch(err => console.error(err));
推荐阅读
- angular - 如何按日期对列表进行分组
- python-3.x - 为具有多重继承的类创建方法(Python)
- javascript - 错误处理承诺在 mongoDB 中保存唯一数据 (ValidationError)
- php - PHP转换拉丁介绍希腊字符
- android - 动态功能模块错误:找不到符号变量 mipmap、菜单、颜色等
- adb - 如何在机器人框架中访问 ADB 命令?[获取已连接安卓设备的设备ID]
- php - 如何在数据表服务器端搜索附加查询
- postgresql - 为什么没有时区的日期时间格式化为有时区?
- mysql - MYSQL - 特定请求慢多计数
- ios - 如果字符串在其中一个值中包含 ("),则 Swift Codable 无法解码