gpt4 book ai didi

javascript - cookie "_shopify_country"来自哪里?

转载 作者:行者123 更新时间:2023-12-02 23:53:17 25 4
gpt4 key购买 nike

我想重定向到与用户在我的 Shopify 网站中浏览的国家/地区关联的商店(基于 Slate) 。

在我的研究过程中,我发现了一个名为_shopify_country的cookie,其值设置为用户的国家/地区,但我不敢使用这个cookie,因为它是undocumented .

我有两个问题:

  1. _shopify_country 设置在哪里?
  2. 如何使用 JavaScript 重定向到与该 Cookie 关联的网站?我应该轮询 cookie 直到它被设置吗?

最佳答案

我浏览了一些 Shopify 网站,但找不到 _shopify_country Cookie。似乎从未设置过,所以我猜这是一个用于获取它的自定义修改,或者可能是一个已弃用的函数。

但是,如果您的目标是确定用户来自哪个国家/地区,您只需向 GEOIP 服务提交 AJAX 请求即可。我倾向于用于 GEO 查找的 API 是 https://www.geojs.io这是一个免费的、未经身份验证的 GEO 查找,

通常,您会显示一个横幅,建议他们更改到本地站点,而不是重定向您自己。对于他们有 VPN/他们为国外某人购买的情况

由于 AJAX 请求是从客户端发出的,因此它将返回示例中的 IP/信息,您可以在控制台中尝试这些。

获取IP

fetch('https://canihazip.com/s')
.then(response => response.text())
.then(body => alert(body))

获取国家代码

fetch('https://get.geojs.io/v1/ip/country')
.then(response => response.text())
.then(body => alert(body))

但是回到问题,如果您想根据国家/地区代码进行重定向,您可以这样做

fetch('https://get.geojs.io/v1/ip/country')
.then(response => response.text())
.then(country_code => {
// Save as a cookie in case we want to use it later / in another page
var date = new Date(); date.setMonth(date.getMonth()+1); date = date.toUTCString();
document.cookie = `_visitor_country=${country_code}; expires=${date}; path=/`;

var domain_and_tld = window.location.host.split('.').splice(-2).join('.');
country_code = country_code.trim().toLowerCase();

switch (country_code) {
case 'gb':
window.location.host = domain_and_tld;
break;
case 'us':
window.location.host = `us.${domain_and_tld}`;
break;
case 'fr':
window.location.host = `fr.${domain_and_tld}`;
break;
};
})
.catch(err => console.error(err));

上面的代码与 ES5 一样/支持旧版浏览器

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://get.geojs.io/v1/ip/country');
xhr.send();
xhr.onload = function() {
if (xhr.status != 200)
return console.error('Error '+xhr.status+': '+xhr.statusText);

var country_code = xhr.response.trim().toLowerCase();

// Save as a cookie, so we can reference this later if we want to
var date = new Date(); date.setMonth(date.getMonth()+1); date = date.toUTCString();
document.cookie = '_visitor_country='+country_code+'; expires='+date+'; path=/';

var domain_and_tld = window.location.host.split('.').splice(-2).join('.');
switch (country_code) {
case 'gb':
window.location.host = domain_and_tld;
break;
case 'us':
window.location.host = 'us.'+domain_and_tld;
break;
case 'fr':
window.location.host = 'fr.'+domain_and_tld;
break;
}
};

xhr.onerror = function() {
console.error('Request failed');
};

关于javascript - cookie "_shopify_country"来自哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55546387/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com