获取功能无限加载(Shopify)

The fetch fonction load infinitely (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));