首页 > 解决方案 > 获取功能无限加载(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));

谢谢你的帮助 :)

标签: javascriptjsoncookiesfetchlocal-storage

解决方案


您似乎想根据用户国家/地区更改查询参数。我们不需要改变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));

推荐阅读