首页 > 解决方案 > 这个脚本地理定位重定向缺少什么

问题描述

我拥有的脚本之一是什么。根据目标国家/地区代码,这不起作用

//OFFER WAP
if (navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/iPhone/i) ||
  navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) ||
  navigator.userAgent.match(/Windows Phone/i) || navigator.userAgent.match(/iPad/i)) {
  var target = []; // 
  target.US = "https://www.google.com"; // 
  target.AU = "https://stackoverflow.com/"; // 
  target.All = "https://www.facebook.com/"; // 
  setTimeout("document.location = urls;", 1500);
}

function geoip(g) {
  window.top.location.href = target[g.country_code] || target.All
}
(function(g, e, o, i, p) {
  i = g.createElement(e), p = g.getElementsByTagName(e)[0];
  i.async = 0;
  i.src = o;
  p.parentNode.insertBefore(i, p)
})(document, 'script', 'http://geoip.nekudo.com/api/?callback=geoip');
<meta charset="utf-8">
<title>Please Wait...</title>
<meta http-equiv="refresh" content="1500">
<script src='http://www.geoplugin.net/javascript.gp' type='text/javascript'></script>

标签: javascripthtmlgeolocationgeo

解决方案


问题是您target在块内部if为各种用户代理进行了初始化。如果用户代理与其中任何一个都不匹配,target则未定义,然后target[g.country_code]出现错误。

您应该在 之前将变量初始化为空对象if,并将默认值放在target.All那里。如果您想要取决于用户代理的位置特定目标,您可以在if.

另一个问题是响应中没有country_code属性。JSON 看起来像:

geoip({
  "city": "Woburn",
  "country": {
    "name": "United States",
    "code": "US"
  },
  "location": {
    "accuracy_radius": 5,
    "latitude": 42.4897,
    "longitude": -71.1595,
    "time_zone": "America/New_York"
  },
  "ip": "71.192.114.133"
});

国家代码在g.country.code,不是g.country_code

var target = { All: "https://www.facebook.com/" };

//OFFER WAP
if (navigator.userAgent.match(/Android/i) || navigator.userAgent.match(/iPhone/i) ||
  navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/BlackBerry/i) ||
  navigator.userAgent.match(/Windows Phone/i) || navigator.userAgent.match(/iPad/i)) {
  target.US = "https://www.google.com"; // 
  target.AU = "https://stackoverflow.com/"; // 
  setTimeout("document.location = urls;", 1500);
}

function geoip(g) {
  window.top.location.href = target[g.country.code] || target.All
}
(function(g, e, o, i, p) {
  i = g.createElement(e), p = g.getElementsByTagName(e)[0];
  i.async = 0;
  i.src = o;
  p.parentNode.insertBefore(i, p)
})(document, 'script', 'http://geoip.nekudo.com/api/?callback=geoip');
<meta charset="utf-8">
<title>Please Wait...</title>
<meta http-equiv="refresh" content="1500">
<script src='http://www.geoplugin.net/javascript.gp' type='text/javascript'></script>


推荐阅读